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