0

In my reduce loop i'm trying to get two arrays from one.I have async logic inside iteration and I get an error as u can see because I've got promise in result on the third iteration and in broke my script. Here i attach my code to show how i do it!

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

Emil Kuluev
  • 25
  • 1
  • 4

1 Answers1

-1

Given that your reduce callback is async, the returned result is a promise. Notice how your log of result is a Promise. To successfully access the value from the previous iteration in the current, you must await that value first.

So instead of

result.readyScoreRequests.push(scoreInfo)

You should await the result to get the inner value.

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

Here is a simplified example of this that should help to clarify:

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])
Jonny
  • 285
  • 2
  • 11
  • Not sure why this was downvoted when the logic is sound? Even if the question itself is considered a duplicate, an answer is independent of that. – Jonny Aug 27 '21 at 18:23