js中forEach异步证明

271 阅读1分钟
  • @Author: yolo
  • @Date: 2021年5月25日

在之前的坑中认识到forEach是异步的,最近学习Promise又遇到了。 想找一下证明forEach是异步案例。

  var p1 = (index) => new Promise((res,rej) => {setTimeout(() => {
    res(index);
  }, 1000)}).then(res=>{
    console.log("执行P1回调"+index);
    console.log(res)
  })
  var arr = [1,2,3]
  for(var i=0;i<arr.length;i++){
    console.log("执行P1_for_"+i)
    await p1(i);
  }
  arr.forEach(async (item,index)=>{
    console.log("执行P1_foreach_"+index)
    await p1(index);
  })

输出结果是: 在这里插入图片描述