RN踩坑‘await‘ expressions are only allowed within async functions and at the top levels of modules.

以前很少在循环中执行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

  • 6
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值