使用Node 4.x。当您有一个Promise.all(promises).then()时,解析数据并将其传递给下一个.then()的正确方法是什么
我想做这样的事情:
Promise.all(promises).then(function(data){
// Do something with the data here
}).then(function(data){
// Do more stuff here
});但我不确定如何将数据传送到第二个.then()。我不能在第一个.then()中使用resolve(...)。我想我可以做到:
return Promise.all(promises).then(function(data){
// Do something with the data here
return data;
}).then(function(data){
// Do more stuff here
});但这似乎不是正确的方法...对此的正确方法是什么?
发布于 2019-09-08 14:23:34
今天,NodeJS支持新的async/await语法。这是一种简单的语法,并使生活变得更容易
async function process(promises) { // must be an async function
let x = await Promise.all(promises); // now x will be an array
x = x.map( tmp => tmp * 10); // proccessing the data.
}
const promises = [
new Promise(resolve => setTimeout(resolve, 0, 1)),
new Promise(resolve => setTimeout(resolve, 0, 2))
];
process(promises)了解更多:
发布于 2020-01-22 02:47:59
你的return data方法是正确的,这是promise chaining的一个例子。如果您从.then()回调返回一个promise,JavaScript将解析该promise并将数据传递给下一个then()回调。
只需小心,并确保您使用.catch()处理错误。Promise.all() rejects as soon as one of the promises in the array rejects。
https://stackoverflow.com/questions/33073509
复制相似问题