2016-11-01 58 views
1

我在承諾鏈中使用Promise.all()。 Promise.all()中的每個promise都返回一個字符串。Node.js - 在promise.all後繼續承諾每個結果promise()

im問題是Promise.all()returns a Promise反對下一個承諾,我想繼續爲每個字符串承諾鏈。

這裏有一個例子:

.... 
    return Promise.all(plugins); 

}) 
.then(function(response) { 

    console.log(response) 
.... 

response樣子:

[ 'results from p1', 'results from p2' ] 

有什麼辦法繼續承諾鏈的每個結果,而不是包含所有的單個對象持續結果如何?

+0

看一看[調用然後之前或之後Promise.all](http://stackoverflow.com/q/36594198/1048572) – Bergi

回答

0

Promise.all(),其設計將返回一個承諾誰的解析值是解決值的你通過它的所有承諾的數組。這就是它的作用。如果這不是你想要的,那麼也許你正在使用錯誤的工具。您可以用多種方式處理各個結果:

首先,您可以遍歷返回結果的數組,並執行任何您想要的操作以進行進一步處理。

Promise.all(plugins).then(function(results) { 
    return results.map(function(item) { 
     // can return either a value or another promise here 
     return .... 
    }); 
}).then(function(processedResults) { 
    // process final results array here 
}) 

其次,你可以在你把它傳遞給Promise.all()附加.then()處理程序到每一個人的承諾。

// return new array of promises that has done further processing 
// before passing to Promise.all() 
var array = plugins.map(function(p) { 
    return p.then(function(result) { 
     // do further processing on the individual result here 
     // return something (could even be another promise) 
     return xxx; 
    }); 
}) 

Promise.all(array).then(function(results) { 
    // process final results array here 
}); 

或者,如果你第三次並不關心,當所有的結果都做,你只是想單獨處理每一個,那麼就不要使用Promise.all()可言。只需附加一個.then()處理程序到每個單獨的承諾,並處理每個結果。

+0

確實很有幫助。感謝您的詳細選項和示例。 – Ben

1

Promise.all需要一個承諾數組。所以插件是一系列的承諾,更重要的是:插件是一個Promise。 所以你可以鏈接你的插件Promise。 因此,這將成爲 Promise.all(plugins.map(function(plugin){ return plugin.then(function(yourPluginString){ return 'example '+ yourPluginString; }) }))

0

您可以像使用https://github.com/Raising/PromiseChain

的工具,實現你說的話作爲

//sc = internalScope 
var sc = {}; 

new PromiseChain(sc) 
    .continueAll([plugin1,plugin2,plugin3],function(sc,plugin){ 
     return plugin(); // I asume this return a promise 
    },"pluginsResults") 
    .continueAll(sc.pluginsResults,function(sc,pluginResult){ 
     return handlePluginResults(pluginResult); 
    },"operationsResults") 
.end(); 

我沒有測試代碼,如果你有任何問題,下午我