以前很少在循环中执行ajax,今天突然遇到个场景用到。习惯使用map来遍历了,结果在map中遍历无法使用await方法。一时有点懵!!!后来发现普通的for循环中可以遍历。虽然不清楚为什么,但是问题总算是解决了。

错误信息

'await' expressions are only allowed within async functions and at the top levels of modules.

错误代码

this.state.citys.map((item)=>{
      await this.loadWetherInfo(item.location);
 });

正确写法

直接使用for循环遍历就可以了。

const {citys} = this.state;
for (let i = 0; i < citys.length; i++) {
  await this.loadWetherInfo(citys[i].location);
}

总结

在for循环中可以使用await,但是在map遍历中不可以使用await。这个小坑竟然浪费了我2个小时😭。
看来需要强化一下Promise的学习了。

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Promise

参考

https://stackoverflow.com/questions/40140149/use-async-await-with-array-map

Logo

技术共进,成长同行——讯飞AI开发者社区

更多推荐