JavaScript数组.reduce与async / await [英] JavaScript array .reduce with async/await

查看:303
本文介绍了JavaScript数组.reduce与async / await的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎有一些问题将async / await与.reduce()结合起来,如下所示:

Seem to be having some issues incorporating async/await with .reduce(), like so:

const data = await bodies.reduce(async(accum, current, index) => {
  const methodName = methods[index]
  const method = this[methodName]
  if (methodName == 'foo') {
    current.cover = await this.store(current.cover, id)
    console.log(current)
    return {
      ...accum,
      ...current
    }
  }
  return {
    ...accum,
    ...method(current.data)
  }
}, {})
console.log(data)

data <$ em>

我知道你可以利用 Promise.all 使用异步循环,但这是否适用于 .reduce()

I know you can utilise Promise.all with async loops, but does that apply to .reduce()?

推荐答案

问题是你的累加器值是承诺 - 它们的返回值是 async functi上秒。为了获得顺序评估(除了最后一次迭代之外的所有迭代),你需要使用

The problem is that your accumulator values are promises - they're return values of async functions. To get sequential evaluation (and all but the last iteration to be awaited at all), you need to use

const data = await array.reduce(async (accumP, current, index) => {
  const accum = await accumP;
  …
}, Promise.resolve(…));

这就是说, async / await 我一般建议使用普通循环代替数组迭代方法 ,它们的性能更高,而且更简单。

That said, for async/await I would in general recommend to use plain loops instead of array iteration methods, they're more performant and often simpler.

这篇关于JavaScript数组.reduce与async / await的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆