我試圖解開一大堆基於回調的節點代碼,它看起來像承諾關鍵,因爲我有很多異步數據庫操作。具體來說,我正在使用藍鳥。對沒有返回數據的函數的承諾
我被困在如何處理需要從數據庫檢索數據並在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
需要,只有當上一個已完成運行,但他們都做(多)異步操作。
這是我對初始化,到目前爲止,但我不知道如何去完成它:
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?
}
}
編輯:雖然鏈接複製的問題,解釋了類似的模式,它沒有相當回答我的問題,因爲它沒有說清楚我可以毫不猶豫地解決承諾。
我的回答對你有幫助嗎?如果是這樣,請點擊複選標記,以便未來的觀衆知道它有幫助。 – Datsik