异步构造 [英] Asynchronous constructor
问题描述
我怎样才能最好地处理类似下面的情况呢?
How can I best handle a situation like the following?
我有一个构造函数,需要一段时间才能完成。
I have a constructor that takes a while to complete.
var Element = function Element(name){
this.name = name;
this.nucleus = {};
this.load_nucleus(name); // This might take a second.
}
var oxygen = new Element('oxygen');
console.log(oxygen.nucleus); // Returns {}, because load_nucleus hasn't finished.
我看到三个选项,每个看起来与众不同。
I see three options, each of which seem out of the ordinary.
一,回调添加到构造。
var Element = function Element(name, fn){
this.name = name;
this.nucleus = {};
this.load_nucleus(name, function(){
fn(); // Now continue.
});
}
Element.prototype.load_nucleus(name, fn){
fs.readFile(name+'.json', function(err, data) {
this.nucleus = JSON.parse(data);
fn();
});
}
var oxygen = new Element('oxygen', function(){
console.log(oxygen.nucleus);
});
两个后,使用EventEmitter发出一个'装'事件。
Two, use EventEmitter to emit a 'loaded' event.
var Element = function Element(name){
this.name = name;
this.nucleus = {};
this.load_nucleus(name); // This might take a second.
}
Element.prototype.load_nucleus(name){
var self = this;
fs.readFile(name+'.json', function(err, data) {
self.nucleus = JSON.parse(data);
self.emit('loaded');
});
}
util.inherits(Element, events.EventEmitter);
var oxygen = new Element('oxygen');
oxygen.on('loaded', function(){
console.log(this.nucleus);
});
也可能是3 ,阻止构造函数。
var Element = function Element(name){
this.name = name;
this.nucleus = {};
this.load_nucleus(name); // This might take a second.
}
Element.prototype.load_nucleus(name, fn){
this.nucleus = JSON.parse(fs.readFileSync(name+'.json'));
}
var oxygen = new Element('oxygen');
console.log(oxygen.nucleus)
但我还没有看到任何这样做过。
But I haven't seen any of this done before.
什么其他的选择呢我?
推荐答案
由于必要性,以避免堵塞节点,使用事件或回调不那么陌生(1)。
Given the necessity to avoid blocking in Node, the use of events or callbacks isn't so strange(1).
通过两个轻微的编辑,你可以用一个合并的:
With a slight edit of Two, you could merge it with One:
var Element = function Element(name, fn){
this.name = name;
this.nucleus = {};
if (fn) this.on('loaded', fn);
this.load_nucleus(name); // This might take a second.
}
...
不过,像 fs.readFile
在你的榜样,核心节点API(至少)经常跟随时的数据,揭露实例静态函数模式准备:
Though, like the fs.readFile
in your example, the core Node APIs (at least) often follow the pattern of static functions that expose the instance when the data is ready:
var Element = function Element(name, nucleus) {
this.name = name;
this.nucleus = nucleus;
};
Element.create = function (name, fn) {
fs.readFile(name+'.json', function(err, data) {
var nucleus = err ? null : JSON.parse(data);
fn(err, new Element(name, nucleus));
});
};
Element.create('oxygen', function (err, elem) {
if (!err) {
console.log(elem.name, elem.nucleus);
}
});
(1)它应该不会很长读取JSON文件。如果是,也许在存储系统中的改变是为了使数据
(1) It shouldn't take very long to read a JSON file. If it is, perhaps a change in storage system is in order for the data.
这篇关于异步构造的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!