0

I am creating small app so that i learn angular, typescript and so on. I find out about reduce function which i can use to sum fields in array. I am trying to implement it in my app but with no luck so far. I have something like this:

    const sumTest: any = data.grades?.map(async (studentNumber) => {
    const getGrade= await dataSources.getStudenGrade(studentNumber);
    return getGrade.grade
    }).reduce((a: any, b: any) =>{ a + b});

That is clearly wrong because i am getting [ Promise { <'pending'> }, Promise { <'pending'> } ] as result. Can somebody help me with that?

1 Answer 1

1

Your mapping result is an array of promises. That's normal; by mapping each item to a promise, you end up with multiple promises.

If you want to asynchronously wait for all the promises to complete, you would use Promise.all:

const sumTest: any = data.grades?.map(async (studentNumber) => {
  const getGrade= await dataSources.getStudenGrade(studentNumber);
  return getGrade.grade;
});
const values = await Promise.all(sumTest);
values.reduce((a: any, b: any) =>{ a + b});
Sign up to request clarification or add additional context in comments.

4 Comments

Hi Stephen. I works but still i am not getting sum. Result is [ 4, 8 ] and another thing typescript is complaining about : Expected an assignment or function call and instead saw an expression.eslint in values.reduce((a: any, b: any) =>{ a + b});. I am calling console.log(values) to get above result.
@Sasa: You should remove the curly braces: values.reduce((a: any, b: any) => a + b);
values.reduce((a: any, b: any) => a + b) console.log(values); I did but result is still: [ 4, 8] it is not summing it.
Ok it works now :):) I have put entire velues.reduce in console log :). Thanks a lot @Stephen

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.