JavaScript 数组 .reduce 和 async/await

标签 javascript promise async-await reduce ecmascript-next

似乎在将 async/await 与 .reduce() 合并时遇到了一些问题,如下所示:

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 对象在 this.store 完成之前被记录...

我知道您可以将 Promise.all 与异步循环一起使用,但这是否适用于 .reduce()

最佳答案

问题是您的累加器值是 promise - 它们是 async function 的返回值。要获得顺序评估(以及除了最后一次迭代之外的所有迭代),您需要使用

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

也就是说,对于async/await,我一般会推荐use plain loops instead of array iteration methods ,它们的性能更高,而且通常更简单。

关于JavaScript 数组 .reduce 和 async/await,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41243468/

相关文章:

javascript - TypeError : $(. ..).easyAutocomplete 不是一个函数

javascript - Bluebird 递归 promise 未得到解决/履行

javascript - promise 返回未定义

node.js - 回调 Promise( Node 7)

asp.net - WebForms 中的 Async/Await - 在页面生命周期结束之前如何继续运行?

javascript - sleep 没有在 async 函数中定义吗?

javascript - 在javascript中获取比选定的键更多的内容

javascript - Java Scripting API——来自 JavaScript 对象的属性始终为 null

javascript - 简单的 for 循环让我陷入循环 - 小数增量错误

javascript - 如果我定义了一个异步函数并在主体中使用了await,那么在调用该函数时是否需要使用await?