如何在nodejs中要求异步

Tua*_*ran 0 node.js promise

我正在使用bluebird来初始化各种类型的数据库连接.

// fileA.js
Promise.all(allConnectionPromises)
    .then(function (theModels) {
        // then i want to do module.exports here
        // console.log here so the expected output
        module.exports = theModels
    })
Run Code Online (Sandbox Code Playgroud)

这样我就可以从另一个文件中请求上面的文件.但如果我这样做,我会{}.

let A = require('./fileA')  // i get {} here
Run Code Online (Sandbox Code Playgroud)

知道怎么做吗?

jfr*_*d00 5

您无法在Javascript中神奇地将异步操作转换为同步操作.因此,异步操作将需要异步编码技术(回调或承诺).在常规编码中也与在模块启动/初始化中一样.

处理这个问题的通常设计模式是给你的模块一个构造函数,你传递一个回调函数,当你调用那个构造函数时,它将在异步结果完成时调用回调,然后再调用任何进一步的代码.异步结果必须在该回调中.

或者,由于您已经在使用promises,因此您只需导出调用代码可以使用的承诺.

// fileA.js
module.exports = Promise.all(allConnectionPromises);
Run Code Online (Sandbox Code Playgroud)

然后,在使用此代码的代码中:

require('./fileA').then(function(theModels) {
    // access theModels here
}, function(err) {
    console.log(err);
});
Run Code Online (Sandbox Code Playgroud)

请注意,这样做时,导出的承诺作为一个方便的缓存theModels,因为这的确所有其他模块也require('./fileA')将得到同样的承诺回来,因而有相同解析值,而无需重新执行后面获取模型的代码.


虽然我认为promises版本可能更清晰,特别是因为你已经在模块中使用了promises,这里是构造函数版本的比较结果:

// fileA.js
var p = Promise.all(allConnectionPromises);

module.exports = function(callback) {
   p.then(function(theModels) {
       callback(null, theModels);
   }, function(err) {
       callback(err);
   });
}
Run Code Online (Sandbox Code Playgroud)

然后,在使用此代码的代码中:

require('./fileA')(function(err, theModels) {
    if (err) {
        console.log(err);
    } else {
        // use theModels here
    }
});
Run Code Online (Sandbox Code Playgroud)