2016-03-18 109 views
1

在下面的代碼示例中,我希望在所有承諾解決後獲得從'main'函數返回的baz變量。在所有承諾解決後返回

exports.foo = function(bar) { 

    var baz; 

    // some kind of promises are here forming array of promises p 
    // some of promises may change the baz variable 

    Promise.all(p).then(() => { 
     // returning expression for main function is here 
     // return baz here // does not work 
    }); 

    // return baz //cannot be done because it would be earlier than all the async promises are resolved 
} 
+1

富()犯規返回任何東西。您必須返回Promise.all.then並在調用方法中處理承諾。 –

+0

如果承諾鏈解決了「baz」並在承諾鏈中繼續工作,那將是最好的。 – MinusFour

+0

有些東西告訴我,這只是因爲僞碼寫入,但它非常重要:它實際上是否返回Promise.all(p).then(()=> {'?沒有'return',它總是會回到undefined – Katana314

回答

0

承諾解決主的回報,所以返回巴茲的承諾,而不是:

exports.foo = function(bar) { 
    var baz; 
    return Promise.all(p).then(() => baz); 
} 

exports.foo(3).then(baz => console.log(baz)).catch(e => console.error(e));