每天在使用的await,为什么不能用在forEach中?

前端下午茶

共 2421字,需浏览 5分钟

 ·

2020-09-18 02:14

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

    function test({
     let arr = [321]
     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

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

end
1
2
3

为什么?

其实原因很简单,那就是 forEach 只支持同步代码

我们可以参考下 Polyfill 版本的 forEach,简化以后类似就是这样的伪代码

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

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

怎么解决?

一般来说解决的办法有2种,for...of和for循环。

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

   async function test({
    let arr = [321]
    await Promise.all(
     arr.map(async item => {
      const res = await fetch(item)
      console.log(res)
     })
    )
    console.log('end')
   }

可以看到并没有按照我们期望的输出。

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

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

    async function test({
     let arr = [321]
     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 = [321]
     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 = [321]
  for (var i=0;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()

第3种方法是使用 while循环

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

test()
  • 要想在循环中使用async await,请使用for...of 或者 for 循环, while循环

forEach支持async await

forEach 在正常情况像下面这么写肯定是做不到同步的,程序不会等一个循环中的异步完成再进行下一个循环。原因很明显,在上面的模拟中,while 循环只是简单执行了 callback,所以尽管 callback 内使用了 await ,也只是影响到 callback 内部。

arr.myforeach(async v => {
    await fetch(v);
});

要支持上面这种写法,只要稍微改一下就好

Array.prototype.myforeach = async function (fn, context = null{
    let index = 0;
    let arr = this;
    if (typeof fn !== 'function') {
        throw new TypeError(fn + ' is not a function');
    }
    while (index < arr.length) {
        if (index in arr) {
            try {
                await fn.call(context, arr[index], index, arr);
            } catch (e) {
                console.log(e);
            }
        }
        index ++;
    }
};

参考链接:

  • async,await与forEach引发的血案
  • 【JS基础】从JavaScript中的for...of说起(下) - async和await

最后



如果你觉得这篇内容对你挺有启发,我想邀请你帮我三个小忙:

  1. 点个「在看」,让更多的人也能看到这篇内容(喜欢不点在看,都是耍流氓 -_-)

  2. 欢迎加我微信「qianyu443033099」拉你进技术群,长期交流学习...

  3. 关注公众号「前端下午茶」,持续为你推送精选好文,也可以加我为好友,随时聊骚。

点个在看支持我吧,转发就更好了


浏览 32
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报