<分区>
我正试图为 Node 理清一大堆基于回调的代码,似乎 promises 是关键,因为我有很多异步数据库操作。具体来说,我正在使用 Bluebird。
我对如何处理需要从数据库检索数据并在 this
上设置特定值的函数感到困惑。我想要实现的最终目标是这样的:
myobj.init().then(function() {
return myobj.doStuff1();
}).then(function() {
return myobj.doStuff2();
}).catch(function(err) {
console.log("Bad things happened!", err);
});
特别是init
,doStuff1
和doStuff2
只需要在前一个完成后运行,但它们都是(多个)异步操作.
这是我到目前为止的 init,但我不知道如何完成它:
Thing.prototype.init = function(force) {
if (!this.isInitialized || force) {
return datbase.query("...").then(function(results){
// ... use results to configure this
}).catch(function(err){
console.log("Err 01");
throw err;
});
} else {
// ???
// No data needs to be retrieved from the DB and no data needs to be returned per-se because it's all stored in properties of this.
// But how do I return something that is compatible with the other return path?
}
}
编辑:虽然链接的重复问题解释了类似的模式,但它并没有完全回答我的问题,因为它没有明确说明我可以什么都不做就解决 promise 。