为啥 await 不能用在 forEach 中

不知道你是否写过相似的代码:

function test() {
     let arr = [3, 2, 1]
     arr.forEach(async item => {
      const res = await fetch(item)
      console.log(res)
     })
     console.log('end')
    }
    
    function fetch(x) {
     return new Promise((resolve, reject) => {
      setTimeout(() => {
       resolve(x)
      }, 500 * x)
     })
    }
    
    test()
复制代码

我当时指望的打印顺序是数组

3
2
1
end
复制代码

结果现实与我开了个玩笑,打印顺序竟然是bash

end
1
2
3
复制代码

为何?异步

其实缘由很简单,那就是 forEach 只支持同步代码async

咱们能够参考下 Polyfill 版本的 forEach,简化之后相似就是这样的伪代码函数

while (index < arr.length) {
      callback(item, index)   //也就是咱们传入的回调函数
    }
复制代码

从上述代码中咱们能够发现,forEach 只是简单的执行了下回调函数而已,并不会去处理异步的状况。 而且你在 callback 中即便使用 break 也并不能结束遍历。post

怎么解决?fetch

通常来讲解决的办法有2种,for...of和for循环。ui

使用 Promise.all 的方式行不行,答案是: 不行 spa

async function test() {
    let arr = [3, 2, 1]
    await Promise.all(
     arr.map(async item => {
      const res = await fetch(item)
      console.log(res)
     })
    )
    console.log('end')
   }
复制代码

能够看到并无按照咱们指望的输出。3d

这样能够生效的缘由是 async 函数确定会返回一个 Promise 对象,调用 map 之后返回值就是一个存放了 Promise 的数组了,这样咱们把数组传入 Promise.all 中就能够解决问题了。可是这种方式其实并不能达成咱们要的效果,若是你但愿内部的 fetch 是顺序完成的,能够选择第二种方式。

第1种方法是使用 for...of

async function test() {
     let arr = [3, 2, 1]
     for (const item of arr) {
      const res = await fetch(item)
      console.log(res)
     }
     console.log('end')
    }
复制代码

这种方式相比 Promise.all 要简洁的多,而且也能够实现开头我想要的输出顺序。

可是这时候你是否又多了一个疑问?为啥 for...of 内部就能让 await 生效呢。

由于 for...of 内部处理的机制和 forEach 不一样,forEach 是直接调用回调函数,for...of 是经过迭代器的方式去遍历。

async function test() {
     let arr = [3, 2, 1]
     const iterator = arr[Symbol.iterator]()
     let res = iterator.next()
     while (!res.done) {
      const value = res.value
      const res1 = await fetch(value)
      console.log(res1)
      res = iterator.next()
     }
     console.log('end')
    }
复制代码

第2种方法是使用 for循环

async function test() {
  let arr = [3, 2, 1]
  for (var i=0;i<arr.length;i++) {
    const res = await fetch(arr[i])
    console.log(res)
  }
  console.log('end')
}
 
function fetch(x) {
 return new Promise((resolve, reject) => {
  setTimeout(() => {
   resolve(x)
  }, 500 * x)
 })
}

test()
复制代码

要想在循环中使用async await,请使用for...of 或者 for 循环

参考连接:

async,await与forEach引起的血案

【JS基础】从JavaScript中的for...of提及(下) - async和await