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的源码


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM