JS Array 的 map() 方法和 await 一起使用
在对数组进行逐个异步操作的时候,想使用 await 来获取操作后的数组,尝试了如下的写法:const resArr = await arr.map(async (item)=>{const resItem = await query(item) // 异步操作return resItem})这样的写法是不正确的,因为 Array.prototype.map() 不会返回一个 Promise。
·
在对数组进行逐个异步操作的时候,想使用 await 来获取操作后的数组,尝试了如下的写法:
const resArr = await arr.map(async (item)=>{
const resItem = await query(item) // 异步操作
return resItem
})
这样的写法是不正确的,因为 Array.prototype.map() 不会返回一个 Promise。
可以采用如下的写法
const promiseArr = arr.map((item)=>{
return query(item)
})
const resArr = Promise.all(promiseArr)
更多推荐




所有评论(0)