简体   繁体   English

在 nodejs/js 中组织异步等待函数

[英]Organising async await functions in nodejs/js

I often use this pattern in organising my code in js/nodejs我经常使用这种模式在 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);
});

But i want to do functionOne and functionTwo in parallel, not waiting for previos to return promise.但是我想并行执行functionOnefunctionTwo ,而不是等待 previos 返回 promise。 Only waiting last one for return.只等最后一个回来。 How can i achieve it?我怎样才能实现它?

If you don't want them to run sequentially, use Promise.all :如果您不希望它们按顺序运行,请使用Promise.all

Promise.all([functionOne(), functionTwo()]).then(([resultOne, resultTwo]) => {
    console.log({resultOne, resultTwo});
}).catch(err => {
    console.log(err);
});

or或者

(async function(){
    const [resultOne, resultTwo] = await Promise.all([functionOne(), functionTwo()]);
    return {resultOne, resultTwo};
}()).then(r => {
    console.log(r);
}).catch(err => {
    console.log(err);
});

You can await a Promise.all():您可以等待 Promise.all():

(async function(){

    const results = await Promise.all([functionOne(), functionTwo()])

    return {
        resultOne: results[0],
        resultTwo: results[1],
    }

}()).then(r=>{
    console.log(r);
}).catch(err=>{
    console.log(err);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM