Node.js-在promise.all()之后为每个结果继续承诺链
我正在承诺链中使用Node.js-在promise.all()之后为每个结果继续承诺链,node.js,promise,es6-promise,Node.js,Promise,Es6 Promise,我正在承诺链中使用Promise.all()。promise.all()中的每个承诺都返回一个字符串 我遇到的问题是Promise.all()对象指向下一个Promise,我希望为每个字符串继续Promise链 举个例子: .... return Promise.all(plugins); }) .then(function(response) { console.log(response) .... 响应如下所示: [ 'results from p1', 'resu
Promise.all()
。promise.all()中的每个承诺都返回一个字符串
我遇到的问题是Promise.all()对象指向下一个Promise,我希望为每个字符串继续Promise链
举个例子:
....
return Promise.all(plugins);
})
.then(function(response) {
console.log(response)
....
响应
如下所示:
[ 'results from p1', 'results from p2' ]
有没有办法继续每个结果的承诺链,而不是继续使用包含所有结果的单个对象?promise.all需要一个承诺数组。所以插件是一系列承诺,更重要的是:插件是一个承诺。 所以你可以把你的插件承诺链起来。 因此,这将成为
Promise.all(plugins.map)函数(plugin){
返回plugin.then(函数(yourPluginString){
返回'example'+yourPluginString;
})
}))
Promise.all()
,按其设计返回单个Promise,其解析值是您传递的所有承诺的解析值数组。它就是这样做的。如果这不是您想要的,那么可能您使用了错误的工具。您可以通过多种方式处理单个结果:
首先,您可以循环返回结果的数组,并对其执行任何您想要的操作以进行进一步处理
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
})
其次,您可以将.then()
处理程序附加到每个承诺,然后再将其传递给promise.all()
或者,第三,如果您并不真正关心何时完成所有结果,并且只想单独处理每个结果,那么根本不要使用Promise.all()
。只需在每个承诺上附加一个.then()
处理程序,并在每个结果发生时进行处理。您可以使用如下工具
并将你所说的付诸实施
//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();
我没有测试代码,如果您有任何问题,请PM me查看非常有用的代码。感谢您提供的详细选项和示例。
//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();