await在forEach不起作用解决【await is a reserved word】

原文链接:https://blog.csdn.net/ssbb1995/article/details/82084800

1.await 只能在 async中使用,如:

async function demo() {

   var res = await testCall()

   console.log(res)

}

  其中 testCall() 是调用的其他方法。

2.await 不能在 forEach 中使用,可以用 for- of 替代,如下:

var arr = [1,2,3,4,5]
for (var curElem of arr) {
   var res = await getById(curElm)
   console.log(res)
}

  其中 getById() 是调用的其他方法。

       forEach已经完成了一次对于循环的封装,当 使用foreach时其实也就相当于调用了一个封装了while或者for循环的函数,这个函数本身并没有使用async/await来处理异步,所以使用时在回调函数里面加上async/await是没有作用的。具体可以查看forEach的源码

猜你喜欢

转载自www.cnblogs.com/vae860514/p/10901947.html