我经常使用这种模式在 js/nodejs 中组织代码
(async function(){
let resultOne = await functionOne();
let resultTwo = await functionTwo();
return {
resultOne: resultOne,
resultTwo: resultTwo,
}
}()).then(r=>{
console.log(r);
}).catch(err=>{
console.log(err);
});
但是我想并行执行functionOne
和functionTwo
,而不是等待previos返回promise。只等最后一位归来。
我怎样才能实现它?
最佳答案
如果您不希望它们按顺序运行,请使用 Promise.all
:
Promise.all([functionOne(), functionTwo()]).then(([resultOne, resultTwo]) => {
console.log({resultOne, resultTwo});
}).catch(err => {
console.log(err);
});
或
(async function(){
const [resultOne, resultTwo] = await Promise.all([functionOne(), functionTwo()]);
return {resultOne, resultTwo};
}()).then(r => {
console.log(r);
}).catch(err => {
console.log(err);
});
关于javascript - 在nodejs/js中组织async wait函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60788578/