如何通过Array.prototype.map()使用异步和等待

You want to execute an async function inside a map() call, to perform an operation on every element of the array, and get the results back.

您想在map()调用中执行一个异步函数,对数组的每个元素执行一个操作,并返回结果。

How can you do so?

你该怎么做?

This is the correct syntax:

这是正确的语法:

const list = [1, 2, 3, 4, 5] //...an array filled with values

const functionWithPromise = item => { //a function that returns a promise
  return Promise.resolve('ok')
}

const anAsyncFunction = async item => {
  return functionWithPromise(item)
}

const getData = async () => {
  return Promise.all(list.map(item => anAsyncFunction(item)))
}

getData().then(data => {
  console.log(data)
})

The main thing to notice is the use of Promise.all(), which resolves when all its promises are resolved.

需要注意的主要事情是Promise.all()的使用,它在所有诺言都得到解决时即会解决。

list.map() returns a list of promises, so in result we’ll get the value when everything we ran is resolved.

list.map()返回一个list.map()列表,因此result是当我们解决所有运行问题时,我们将获得该值。

Remember, we must wrap any code that calls await in an async function.

请记住,我们必须将调用await所有代码包装在async函数中。

See the promises article for more on promises, and the async/await guide.

有关诺言的更多信息,请参见诺言文章 ,以及async / await指南

翻译自: https://flaviocopes.com/javascript-async-await-array-map/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值