Node.js – 对promise.all()后的每个结果继续承诺链

我在承诺链中使用Promise.all() 。 Promise.all()中的每个promise都返回一个string。

即时通讯的问题是,Promise.all() 返回Promise对象到下一个承诺,我想继续对每个string承诺链。

下面是一个例子:

 .... return Promise.all(plugins); }) .then(function(response) { console.log(response) .... 

response如下所示:

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

有没有办法继续每个结果的承诺链,而不是继续使用包含所有结果的单个对象?

Promise.all() ,通过它的devise返回一个单一的承诺,谁解决了价值是所有你传递的承诺的解决价值数组。 这就是它的作用。 如果这不是你想要的,那么也许你正在使用错误的工具。 您可以通过多种方式处理各个结果:

首先,你可以遍历返回的结果数组,并做任何你想与他们进行进一步处理。

 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()之前,可以为每个单独的promise添加一个.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()处理程序附加到每个单独的承诺,并在发生时处理每个结果。

Promise.all期待一系列的承诺。 所以插件是一系列的承诺,更重要的是:插件是一个承诺。 所以你可以链接你的插件Promise。 Promise.all(plugins.map(function(plugin){ return plugin.then(function(yourPluginString){ return 'example '+ yourPluginString; }) }))

你可以使用像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(); 

如果你有任何问题,我没有testing代码