I need to push to an array located to uppser scope of forEach
loop. In each it calls a promise with a value, and pushes the result to the array.
function getSquareOfEvenNumber(num) {
return new Promise((resolve, reject) =>{
if (num % 2 !== 0 ) reject('Please pass a even number only!');
resolve(num * num);
})
}
const getResult = (a) => {
let resultants = [6];
let totalErrors = 0;
a.forEach(async (e) => {
try {
const d = await getSquareOfEvenNumber(e)
resultants.push(d)
} catch(err) {
totalErrors++;
}
})
return {
resultants,
totalErrors,
resultantCount: resultants.length
};
}
Also, I have tried below.
a.forEach(async (e) => {
getSquareOfEvenNumber(e)
.then((d) => resultants.push(d))
.catch((err) => resultants++)
})
Also, tried with for...of
loop.
for (e of a) {
getSquareOfEvenNumber(e)
.then((d) => resultants.push(d))
.catch((err) => resultants++)
}
But
it's also not working, I am getting the initial values of the upper variables. They are not being modified in the loop.
{ resultants: [ 6 ], totalErrors: 0, resultantCount: 1 }
Please someone explain why this is happening and if there is any workaround.