猿问

js for 在等待时是否阻塞?

const somefunction = async () => {

  const arr = [...]

  for(let i = 0 ; i < arr.length ; ++i){

    await updater(arr[i])

  }

}

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


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


湖上湖
浏览 137回答 2
2回答

凤凰求蛊

不,它没有阻塞。asyncawait函数在执行承诺时进入睡眠状态。控制权交还给调用函数(该函数获取从async函数返回的未解决的 Promise)。(当然,如果updater是阻塞,那么它仍然会阻塞)。

烙印99

正如您通过运行此示例所看到的,该函数将是非阻塞的。这就是异步等待的本质。&nbsp; &nbsp; function asyncAction(message) {&nbsp; &nbsp; &nbsp; &nbsp; console.log("asyncAction start: " + message)&nbsp; &nbsp; &nbsp; &nbsp; return new Promise ( (res, err) => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; setTimeout( () => res("done"),2000)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; )&nbsp; &nbsp; &nbsp; &nbsp; console.log("asyncAction complete: " + message)&nbsp; &nbsp; }&nbsp; &nbsp;&nbsp; &nbsp; async function asyncActions() {&nbsp; &nbsp; &nbsp; &nbsp; await asyncAction("1")&nbsp; &nbsp; &nbsp; &nbsp; console.log("1 done")&nbsp; &nbsp; &nbsp; &nbsp; await asyncAction("2")&nbsp; &nbsp; &nbsp; &nbsp; console.log("2 done")&nbsp; &nbsp; &nbsp; &nbsp; await asyncAction("3")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; console.log("3 done")&nbsp; &nbsp; }&nbsp; &nbsp;&nbsp; &nbsp; console.log("program start")&nbsp; &nbsp; asyncActions()&nbsp; &nbsp; console.log("program complete")
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答