我目前在nodejs中有一些js文件,这些文件作为模块加载并扩展了app对象(使用express)。
所以他们的签名看起来像:
module.exports = function(app, callback) {
// ...
callback();
}
因此,目前大约有5个,我的代码如下:
require("./setup/a")(app, function() {
require("./setup/b")(app, function(){
require("./setup/c")(app, function(){
require("./setup/d")(app, function(){
require("./setup/e")(app, function(){
startApp();
})
})
})
})
});
现在看起来不雅观,作为其“厄运的金字塔”,但我不完全相信我需要如何改变这种模式使用Q,因为我是假设我会使用Q.fcall(...a).then(...b).etc.done()
。但是我不确定如何将应用程序传递给它,以及是否需要返回回调以使其作为承诺进行处理。
理想情况下,我不想在代码中全力以赴,只希望在要删除金字塔用例的地方使用Q,因此在上面的示例中,我如何结合使用Q和Promise将应用程序传递到每个必需的模块中然后在最后启动应用程序?
假设您的模块尚未使用promise,您可以执行以下操作:
module.exports = function(app) {
// do some stuff with app
return new Promise(function(resolve,reject){
// when ready to resolve after some actions on app
resolve(); // you can also return a value here as a cb param
});
};
Promise.all(["./setup/a","./setup/b","./setup/c"].map(require.bind(null,app)))
.then(startApp);
但是,您应该在尽可能低的级别上使用promise,这意味着您可以简单地返回在过程中使用的promise:
module.exports = function(app){
return something(app).then(function(){
return somethingElseAsyncWithApp(app);
});
};
因此,promise构造器不是必需的。请注意,此答案使用本机承诺,但也适用于使用该语法的库(例如Bluebird)。对于Q值变new Promise
到new Q.Promise
和Promise.all
到Q.all
。
或者,你可以改变每require(x)
到Q.fcall(require,x)
和使用Q.all
直接,但既慢(虽然Q是慢反正)和更多的错误不是直接promisifying模块容易。最好尽可能保证最低级别的API。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句