在对数组进行逐个异步操作的时候,想使用 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)
Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐