使用异步逻辑减少

Reduce with async logic

在我的 reduce 循环中,我试图从 one.I 获取两个数组,它们在迭代中具有异步逻辑,如您所见,我得到了一个错误,因为我在第三次迭代中得到了结果承诺,并且打破了我的剧本。在这里我附上我的代码来展示我是如何做到的!

const {
    readyScoreRequests,
    remainingScores,
  } = await scoreRequests.reduce(async (result, score) => {
    const { profile } = score;
    console.log('result', result);
    const importedScore = score.scoreId ? await importedScoreService.findOne({
      where: { id: score.scoreId },
    }) : null;
    const scoreDate = importedScore ? moment(importedScore.createdOn).format('MM/DD/YYYY') : 'New Score';

    const scoreInfo = {
      status: score.status.charAt(0).toUpperCase() + score.status.slice(1),
      scoreDate,
      name: profile ? profile.name : null,
      email: score.companyEmail ? score.companyEmail : null,
      city: profile ? profile.city : null,
      state: profile ? profile.state : null,
      logo: profile ? profile.logo : null,
    };

    if (score.status === 'ready') {
      result.readyScoreRequests.push(scoreInfo);
      return result;
    }

    result.remainingScores.push(scoreInfo);
    return result;
  }, { readyScoreRequests: [], remainingScores: [] });

error in terminal

鉴于您的 reduce 回调是异步的,返回的结果是一个承诺。请注意您的 result 日志是如何成为 Promise 的。要在当前迭代中成功访问上一次迭代的值,您必须首先 await 该值。

所以不用

result.readyScoreRequests.push(scoreInfo)

您应该等待结果以获取内在价值。

const resultRes = await result
resultRes.readyScoreRequests.push(scoreInfo)

这是一个简化的例子,应该有助于澄清:

function multiply(value){
    return new Promise(res => {
        setTimeout(() => {
            res(value*2)
        }, 100)
    })
}

async function runSum(values){
    const sum = await values.reduce(async (acc, cur) => {
        const value = await multiply(cur)
        const accRes = await acc
        return accRes + value
    }, 0)
    console.log(sum)
}

runSum([1,2,3,4])