一个没有返回数据的函数的承诺

我试图解开一大堆基于callback的节点代码,它看起来像承诺的关键,因为我有很多的asynchronous数据库操作。 具体来说,我正在使用蓝鸟。

我被困在如何处理一个函数,需要从数据库检索数据,并设置一定的值。 我试图完成的最终目标是这样的:

 myobj.init().then(function() { return myobj.doStuff1(); }).then(function() { return myobj.doStuff2(); }).catch(function(err) { console.log("Bad things happened!", err); }); 

特别是initdoStuff1doStuff2只有在前一个完成doStuff2需要运行,但是它们都执行(多个)asynchronous操作。

到目前为止,这是我对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? } } 

编辑:虽然重复的问题链接解释了类似的模式,它并没有完全回答我的问题,因为它没有说清楚我可以解决一个没有任何承诺。

如果我正确理解你的问题,你可以做一些事情:

 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"); reject(err); 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? return Promise.resolve(); } } } 

只要return Promise.resolve(); 从你的其他function。