Reputation: 51
I have the following array of objects
const people = [
{
id:'John:1:Aries',
exp:40.3,
scores: [4, 4, 5, 6, 4, 6, 5],
futureScores:Promise.resolve([5, 5, 6]),
},
{
id:'Jane:2:Pisces',
exp:57.6,
scores: [6, 5, 6, 6, 4, 5, 6],
futureScores:Promise.resolve([4, 5, 6]),
},
{
id:'Tom:3:Leo',
exp:30.3,
scores: [4, 4, 5, 5, 6, 6],
futureScores:Promise.resolve([4, 4, 6]),
},
{
id:'Amy:4:Sagittarius',
exp:35.0,
scores: [6, 6, 6, 6, 6, 5],
futureScores:Promise.resolve([6, 5, 6]),
},
];
const extractId = (people) => {
return people.filter((person) => {
const id = person.id;
if(id.includes("a")){
return person;
}
})
}
const scores = extractId(people);
const avg = (scores) => {
const getavg = scores.map((el) => el.scores.reduce((a,b) => a +b , 0)/el.scores.length);
const allavg = getavg.reduce((a, b) => a+b/getavg.length, 0)
return allavg;
}
I want to access the futureScores property and record the scores in another variable Tried the following
const future = (scores) => {
const arr = [];
const fscore = scores.map((el) => {
const fscores = el.futureScores;
const result = fscores.then(function(value){
console.log(value);
arr.concat.value;
});
return result
})
return fscore;
}
console.log(future(scores));
The first console.log is outputting the scores but console.log(future(scores)) is outputting [ Promise { }, Promise { } ] What am I doing wrong?
Upvotes: 0
Views: 56
Reputation: 577
It's how you're handling promises within a map. The idea is you should return a map of promises and resolve them. Something like this:
const future = (scores) => {
return scores.map((el) => {
const fscores = el.futureScores;
return fscores.then((value) => value);
})
}
Promise.all(future(scores)).then(res=> {
console.log(res)
})
The idea is to return fscore
which is a single promise but since it's a map, at the end we have an array of promises which we can resolve with Promise.all
I did away with arr.concat.value since you're not using it. And if you want to actually change the array, do arr = arr.concat.value;
since concat does not mutate the original array, makes a new one.
Upvotes: 1
Reputation: 44
You need to return the array inside of the map function.
const future = (scores) => {
const arr = [];
const fscore = scores.map((el) => {
const fscores = el.futureScores;
const result = fscores.then(function(value){
console.log(value);
return arr.concat.value;
});
return result
})
return fscore;
}
future(scores).forEach( val => {
console.log(val)
})
Upvotes: 0