Reputation: 35
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?
Upvotes: 0
Views: 246
Reputation: 456507
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});
Upvotes: 1