JavaScript数组.reduce与async/await

162

似乎在将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)

this.store 完成之前,data 对象被记录下来...

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

11个回答

0

另一个经典选项是使用Bluebird

const promise = require('bluebird');

promise.reduce([1,2,3], (agg, x) => Promise.resolve(agg+x),0).then(console.log);

// Expected to product sum 6

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接