【问题标题】:Reduce with async logic [duplicate]使用异步逻辑减少 [重复]
【发布时间】:2021-10-23 05:52:15
【问题描述】:

在我的 reduce 循环中,我试图从一个数组中获取两个数组。我在迭代中有异步逻辑,并且我得到了一个错误,正如你所看到的,因为我在第三次迭代中得到了结果,并且破坏了我的脚本.在这里我附上我的代码来展示我是如何做到的!

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

【问题讨论】:

    标签: javascript node.js asynchronous promise reduce


    【解决方案1】:

    鉴于您的 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])

    【讨论】:

    • 不知道为什么在逻辑合理的情况下这被否决了?即使问题本身被认为是重复的,答案也是独立的。
    猜你喜欢
    • 1970-01-01
    • 2010-10-14
    • 1970-01-01
    • 1970-01-01
    • 2020-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多