首页 > 解决方案 > Parallel vs Series - 如何使用异步按顺序执行函数

问题描述

根据 google docs 对 Async 的解释,以下名为“parallel”的函数应并行执行,而名为“series”的函数应按顺序执行。
Google Developers 上的异步函数说明

并行应该需要 2 秒才能完成。
系列应该需要 4 秒。
但是,它们都在 2 秒内完成。

为什么 series() 总共不需要 4 秒?我期待第一个计时器在 2 秒后完成,然后第二个计时器在 2 秒后完成?

async function series() {
    function timer(time) { setTimeout(function(){ console.log(`Hello ${time}`) }, time); }

    await timer(2000);  // Wait 2 seconds…
    await timer(2000);  // …should wait another 2 seconds
}
series()  // should take 4 seconds to complete, but only takes 2 seconds

为什么这可以并行工作,但系列不能串联工作?

async function parallel() {
    function timer(time) { setTimeout(function(){ console.log(`Hello ${time}`) }, time); }

    let one = timer(2000);  // Start a 2 second timer asynchronously…
    let two = timer(2000);  // …meaning this timer happens in parallel. 
    await one;  // Wait 2 seconds for the first timer
    await two;  // …by which time this time finishes around same time
}
parallel()  // completes in 2 seconds

标签: javascriptasynchronousasync-await

解决方案


await 运算符用于等待 Promise。如果你让你的计时器函数返回一个在调用超时回调时解决的承诺,那么它应该像你期望的那样工作。

你可以在这里阅读更多:承诺 等待


推荐阅读