你不能神奇地让一个异步操作成在JavaScript中的同步操作。所以,异步操作需要异步编码技术(回调或承诺)。常规编码和模块启动/初始化一样。
处理这个问题的通常设计模式是给你的模块一个构造函数,你传递一个回调给你,当你调用构造函数时,它会在异步结果完成时调用回调,使用该异步结果的代码必须位于该回调中。
或者,因为你已经在使用的承诺,你可以导出调用代码可以使用一个承诺。
// fileA.js
module.exports = Promise.all(allConnectionPromises);
然后,在代码中使用此:
require('./fileA').then(function(theModels) {
// access theModels here
}, function(err) {
console.log(err);
});
注意,这样做时,导出的承诺充当theModels
方便的高速缓存也因为这确实require('./fileA')
会得到所有其他模块相同的承诺回来,因此相同的解决价值,而不需要重新执行获取模型的代码。
虽然我觉得承诺版本可能是清洁尤其是你已经在使用该模块内的承诺,因为,这里的构造函数的版本会是什么样子进行比较:
// fileA.js
var p = Promise.all(allConnectionPromises);
module.exports = function(callback) {
p.then(function(theModels) {
callback(null, theModels);
}, function(err) {
callback(err);
});
}
然后,在代码使用此:
require('./fileA')(function(err, theModels) {
if (err) {
console.log(err);
} else {
// use theModels here
}
});
您是否符合参数promise.all是prmises数组? – null1941
@ null1941是我没有 –
查收承诺是没有错误的exec? – null1941