数组 reduce 方法 + promises

Array reduce method + promises

我有一个函数,它从当前路径获取数据以创建一个数组 ([x, y, z, a, b]),然后将其传递给 reduce 方法以 return 一个新的对象数组。我想将初始数组中的每个值传递给一个 return 对象的函数,并将该对象添加到新数组中。但是在它结束并且我 console.log accumulate 没有打印任何内容之后,我该如何使用 promises 来完全显示 accumulate 的结果?

let accumulate = path.search
      .substring(1)
      .split("+")
      .reduce((acc, val) => {
        FetchMovie(val).then((res) => {
          acc.push(res);
        });
        return acc;
      }, []);

您传递给 .then() 的方法是异步执行的,因此 acc 在您的 reduce 操作完成之前不会被填充(为时已晚)。您可以使用 Promise.all(),首先将所有值映射 (.map()) 到 FetchMovie 函数返回的 Promise:

let accumulatedPromise = Promise.all(path.search
      .substring(1)
      .split("+").map(val => FetchMovie(val)));

accumulatedPromise
  .then(results => console.log(results))
  .catch(err => console.error(err));

你不能在 reducer 中使用 promises,除非你首先 resolve 所有的 promise。一个简单的方法是拆分字符串,return 新的 Promise,然后等待所有的 promise 完成。

这是一个例子:

const lst = [1, 2, 3, 4, 5, 6]; // results after your `split`

Promise.all(
  // replacing `reduce` for `map`
  lst.map(val => FetchMovie(val))
).then(
  // log the new array
  newArray => console.log(newArray)
)