【问题标题】:Array reduce method + promises数组减少方法 + 承诺
【发布时间】:2021-07-30 21:03:37
【问题描述】:

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

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

【问题讨论】:

    标签: javascript arrays es6-promise reduce


    【解决方案1】:

    你传递给.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));
    

    【讨论】:

      【解决方案2】:

      你不能在 reducer 中使用 Promise,除非你先解决所有的 Promise。一个简单的方法是拆分字符串,返回新的 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)
      )
      

      【讨论】:

        猜你喜欢
        • 2021-09-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-12-21
        • 1970-01-01
        • 1970-01-01
        • 2020-04-27
        相关资源
        最近更新 更多