鉴于有必要避免在Node中进行阻塞,事件或回调的使用并不奇怪(1)。
稍加修改为2,即可将其与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您的示例中一样,核心Node API(至少)通常遵循静态函数的模式,这些静态函数会在数据准备就绪时公开实例:
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文件应该不需要很长时间。如果是这样,则可能是为了更改数据而更改了存储系统。



