据我所知,在ES7/ES2016中,在代码中放置多个await将类似于用promise链接.then(),这意味着它们将一个接一个地执行,而不是并行执行。例如,我们有以下代码:

await someCall();
await anotherCall();

我是否正确理解只有当someCall()完成时才会调用另一个otherCall()?并行调用它们最优雅的方式是什么?

我想在Node中使用它,所以也许有一个异步库的解决方案?

编辑:我对这个问题中提供的解决方案不满意:由于异步生成器中的非并行等待承诺,所以速度变慢,因为它使用生成器,我问的是一个更通用的用例。


当前回答

您可以调用多个异步函数,而无需等待它们。这将并行执行它们。执行此操作时,将返回的Promise保存在变量中,并在某个时刻单独或使用Promise.all()等待它们,然后处理结果。

还可以使用try…包装函数调用。。。catch处理单个异步操作的失败并提供回退逻辑。

下面是一个示例:观察日志,在单个异步函数开始执行时打印的日志会立即打印,即使第一个函数需要5秒才能解析。

函数someLongFunc(){return new Promise((resolve,reject)=>{console.log('执行功能1')setTimeout(分辨率,5000)})}函数另一个LongFunc(){return new Promise((resolve,reject)=>{console.log('执行功能2')setTimeout(分辨率,5000)})}异步函数main(){让某个LongFuncPromise,另一个LongFunc Promiseconst start=Date.now()尝试{someLongFuncPromise=someLongFunc()}捕获(ex){console.error('功能1期间出现问题')}尝试{anotherLongFuncPromise=另一个LongFunc()}捕获(ex){console.error('功能2期间出现问题')}等待某人LongFuncPromise等待另一个LongFuncPromiseconst totalTime=Date.now()-开始console.log('执行完成时间',totalTime)}main()

其他回答

我投票支持:

await Promise.all([someCall(), anotherCall()]);

请注意,调用函数时,可能会导致意外结果:

// Supposing anotherCall() will trigger a request to create a new User

if (callFirst) {
  await someCall();
} else {
  await Promise.all([someCall(), anotherCall()]); // --> create new User here
}

但以下始终会触发创建新用户的请求

// Supposing anotherCall() will trigger a request to create a new User

const someResult = someCall();
const anotherResult = anotherCall(); // ->> This always creates new User

if (callFirst) {
  await someCall();
} else {
  const finalResult = [await someResult, await anotherResult]
}

我创建了一个助手函数waitAll,也许它可以让它更甜。它目前只在nodejs中工作,在浏览器chrome中不工作。

    //const parallel = async (...items) => {
    const waitAll = async (...items) => {
        //this function does start execution the functions
        //the execution has been started before running this code here
        //instead it collects of the result of execution of the functions

        const temp = [];
        for (const item of items) {
            //this is not
            //temp.push(await item())
            //it does wait for the result in series (not in parallel), but
            //it doesn't affect the parallel execution of those functions
            //because they haven started earlier
            temp.push(await item);
        }
        return temp;
    };

    //the async functions are executed in parallel before passed
    //in the waitAll function

    //const finalResult = await waitAll(someResult(), anotherResult());
    //const finalResult = await parallel(someResult(), anotherResult());
    //or
    const [result1, result2] = await waitAll(someResult(), anotherResult());
    //const [result1, result2] = await parallel(someResult(), anotherResult());

    // A generic test function that can be configured 
    // with an arbitrary delay and to either resolve or reject
    const test = (delay, resolveSuccessfully) => new Promise((resolve, reject) => setTimeout(() => {
        console.log(`Done ${ delay }`);
        resolveSuccessfully ? resolve(`Resolved ${ delay }`) : reject(`Reject ${ delay }`)
    }, delay));

    // Our async handler function
    const handler = async () => {
        // Promise 1 runs first, but resolves last
        const p1 = test(10000, true);
        // Promise 2 run second, and also resolves
        const p2 = test(5000, true);
        // Promise 3 runs last, but completes first (with a rejection) 
        // Note the catch to trap the error immediately
        const p3 = test(1000, false).catch(e => console.log(e));
        // Await all in parallel
        const r = await Promise.all([p1, p2, p3]);
        // Display the results
        console.log(r);
    };

    // Run the handler
    handler();
    /*
    Done 1000
    Reject 1000
    Done 5000
    Done 10000
    */

虽然设置p1、p2和p3并不是严格地并行运行它们,但它们不会阻碍任何执行,您可以通过捕获捕获上下文错误。

这可以通过Promise.allSettled()实现,它类似于Promise.all(),但没有快速失败行为。

async function Promise1() {
    throw "Failure!";
}

async function Promise2() {
    return "Success!";
}

const [Promise1Result, Promise2Result] = await Promise.allSettled([Promise1(), Promise2()]);

console.log(Promise1Result); // {status: "rejected", reason: "Failure!"}
console.log(Promise2Result); // {status: "fulfilled", value: "Success!"}

注意:这是一个边缘功能,浏览器支持有限,因此我强烈建议为该功能添加polyfill。

在我的例子中,我有几个任务要并行执行,但我需要对这些任务的结果做一些不同的事情。

function wait(ms, data) {
    console.log('Starting task:', data, ms);
    return new Promise(resolve => setTimeout(resolve, ms, data));
}

var tasks = [
    async () => {
        var result = await wait(1000, 'moose');
        // do something with result
        console.log(result);
    },
    async () => {
        var result = await wait(500, 'taco');
        // do something with result
        console.log(result);
    },
    async () => {
        var result = await wait(5000, 'burp');
        // do something with result
        console.log(result);
    }
]

await Promise.all(tasks.map(p => p()));
console.log('done');

输出:

Starting task: moose 1000
Starting task: taco 500
Starting task: burp 5000
taco
moose
burp
done

(异步函数(){功能等待(毫秒,数据){console.log('启动任务:',数据,毫秒);return new Promise(resol=>setTimeout(resolve,ms,data));}var任务=[异步()=>{var result=等待等待(1000,'moose');//做些有结果的事console.log(结果);},异步()=>{var result=等待等待(500,'taco');//做些有结果的事console.log(结果);},异步()=>{var result=等待等待(5000,'burp');//做些有结果的事console.log(结果);}]await Promise.all(tasks.map(p=>p()));console.log(“one”);})();