2016-12-14 41 views
0

我有一個函數的函數,如何使用,使用的承諾

asdf() { 
    var a = fooController.getOrCreateFooByBar(param); 
    console.log("tryna do thing"); 
    console.log(a); //undefined 
    if (!a.property) { 
     //blah 
    } 

是死亡的結果。 getOrCreateFooByBar做了

Model.find({phoneNumber : number}).exec() 
    .then(function(users) {}) 

,並尋找或創建模式,在年底返回它:

.then(function(foo) { return foo} 

如何使用的這asdf()結果呢?我覺得這是一個相當簡單的問題,但我陷入困境。如果我嘗試執行a.exec()或a.then(),那麼'我無法讀取未定義的屬性'錯誤。

回答

2

Promise(與傳遞迴調相對)的主要思想是它們是可以傳遞並返回的實際對象。

fooController.getOrCreateFooByBar需要返回它從Model.find()(在完成所有處理之後)得到的Promise。然後,您可以在asdf函數中的a中訪問它。

反過來,asdf()應該返回一個承諾,這也將使asdf()以及。只要你不斷從異步函數返回Promises,你就可以繼續鏈接它們。

// mock, you should use the real one 
const Model = { find() { return Promise.resolve('foo'); } }; 

function badExample() { 
    Model.find().then(value => doStuff(value)); 
} 

function goodExample() { 
    return Model.find().then(value => doStuff(value)); 
} 

function asdf() { 
    var a = badExample(); 
    var b = goodExample(); 

    // a.then(whatever); // error, a is undefined because badExample doesn't return anything 

    return b.then(whatever); // works, and asdf can be chained because it returns a promise! 
} 

asdf().then(valueAfterWhatever => doStuff(valueAfterWhatever));
+0

啊,這是有道理的。我沒有做'return Model.find({...'謝謝! – ahota

+0

[Return all the promises](http://stackoverflow.com/a/37084467/918910)。 – jib