2016-02-27 30 views
1

我試圖解開一大堆基於回調的節點代碼,它看起來像承諾關鍵,因爲我有很多異步數據庫操作。具體來說,我正在使用藍鳥。對沒有返回數據的函數的承諾

我被困在如何處理需要從數據庫檢索數據並在this上設置特定值的函數。最終的目標,我要完成的是一樣的東西:

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

特別initdoStuff1doStuff2需要,只有當上一個已完成運行,但他們都做(多)異步操作。

這是我對初始化,到目前爲止,但我不知道如何去完成它:

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? 
    } 
} 

編輯:雖然鏈接複製的問題,解釋了類似的模式,它沒有相當回答我的問題,因爲它沒有說清楚我可以毫不猶豫地解決承諾。

+0

我的回答對你有幫助嗎?如果是這樣,請點擊複選標記,以便未來的觀衆知道它有幫助。 – Datsik

回答

2

如果我正確理解你的問題,你可以這樣做:

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();從您的其他功能。

+0

避免['Promise'構造函數反模式](http://stackoverflow.com/q/23803743/1048572) – Bergi

+0

@Bergi我想我修好了嗎?從來沒有聽說過這個,但它是好東西。 – Datsik

+0

是的,就是這樣。 – Bergi