使用 reduce 和 await 给出不同的结果

Using reduce with await give different result

我有一个带有异步函数的 reduce 和另一个没有异步函数的 reduce,给定相同的参数结果不同,我不明白为什么:

没有异步的例子:

function output(inp) {
    document.body.appendChild(document.createElement('pre')).innerHTML = inp;
}

const listOfMonths = [
  "2020-01",
  "2020-02",
  "2020-03",
  "2020-04",
  "2020-05",
  "2020-06"
];

const reduceWithoutAsync = listOfMonths.reduce(
        (previousKpis, curr, index) => {
          return {
            ...previousKpis,
            [curr]: "Hello Mars"
          };
        },
        {}
      );
      
output(JSON.stringify(reduceWithoutAsync, null, 4))

使用异步:

function output(inp) {
    document.body.appendChild(document.createElement('pre')).innerHTML = inp;
}

const listOfMonths = [
  "2020-01",
  "2020-02",
  "2020-03",
  "2020-04",
  "2020-05",
  "2020-06"
];

listOfMonths.reduce(async (previousKpis, curr, index) => {
  return Promise.resolve({
           ...previousKpis,
           [curr]: await Promise.resolve("hello Mars")
         });
    },
  Promise.resolve({})
).then(result => output(JSON.stringify(result, null, 4)));
      

为什么我在使用异步时只有最后一个元素?

在您的 return 语句之前添加 const previousKpis = await previousKpis

您提供的每个 reduce 函数都是一个异步函数,这意味着它 return 是一个承诺。即使您在该承诺中调用 return,您仍然需要等待它。我相信你在 previousKpis 解决之前传播它。

function output(inp) {
    document.body.appendChild(document.createElement('pre')).innerHTML = inp;
}

const listOfMonths = [
  "2020-01",
  "2020-02",
  "2020-03",
  "2020-04",
  "2020-05",
  "2020-06"
];

listOfMonths.reduce((previousKpis, curr, index) => (
        previousKpis.then(async prev => ({
            ...prev,
            [curr]: await Promise.resolve("hello Mars")
        }))
    ),
    Promise.resolve({})
).then(result => output(JSON.stringify(result, null, 4)));
      

previousKpis 是一个 Promise,因此您需要 await 它或使用 then,就像我在示例中所做的那样。到时候应该就没事了!