【问题标题】:js for is blocking or not when awaiting?js for 在等待时是否阻塞?
【发布时间】:2020-11-01 15:35:25
【问题描述】:
const somefunction = async () => {
  const arr = [...]
  for(let i = 0 ; i < arr.length ; ++i){
    await updater(arr[i])
  }
}

上面的for循环会等待promise解决后再进行下一次迭代,但是,这现在是nodejs中主事件循环的阻塞动作吗?

请注意:这是一个“for”而不是“forEach”循环。很不一样。

【问题讨论】:

标签: javascript async-await


【解决方案1】:

不,它没有阻塞。

async 函数在 await 执行承诺时进入睡眠状态。控制权交还给调用函数(它获取从async 函数返回的未解决的 Promise)。

(当然,如果updater 正在阻塞,那么它仍然会阻塞)。

【讨论】:

  • 但是处理大数组的for循环会被认为是阻塞不?
  • @John — 如果“处理”意味着awaiting 一个实际上是异步的 Promise,则不是。
  • 好的,谢谢。我找不到任何关于你所说的具体文档,你碰巧知道吗。我一直登陆developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…,我认为这是不正确的
  • 引用:“await 表达式会导致异步函数执行暂停,直到 Promise 被解决(即完成或拒绝),并在完成后恢复异步函数的执行……允许await 的函数在 await 函数的延迟继续之前恢复执行。在 await 延迟其函数的继续之后,如果这是该函数执行的第一个 await,则立即执行也会继续通过向函数的调用者返回一个挂起的 Promise完成 await 的功能并恢复执行该调用者”
【解决方案2】:

正如您通过运行此示例所看到的,该函数将是非阻塞的。这就是异步等待的本质。

    function asyncAction(message) {
        console.log("asyncAction start: " + message)
        return new Promise ( (res, err) => {
                                            setTimeout( () => res("done"),2000)
                                            }
        )
        console.log("asyncAction complete: " + message)
    }   

    async function asyncActions() {
        await asyncAction("1")
        console.log("1 done")
        await asyncAction("2")
        console.log("2 done")
        await asyncAction("3")              
        console.log("3 done")
    }   

    console.log("program start")
    asyncActions()
    console.log("program complete")

【讨论】:

  • 是的,这演示了异步的作用,但问题更具体地与它在 for 循环中的行为方式有关。
猜你喜欢
  • 2011-08-04
  • 1970-01-01
  • 2022-01-04
  • 1970-01-01
  • 1970-01-01
  • 2016-06-11
  • 2021-09-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多