I have a function where I form the current sum of elements. Getcoin is the method in my Api, and it works correctly if I console.log each element during the foreach cycle. But as the result I got nothing in the return and console.log function
getCurrentCost() {
let currentCostArr = [];
let sum = 0;
let existingEntries = JSON.parse(localStorage.getItem("walletData"));
if (existingEntries == null) existingEntries = [];
existingEntries.forEach(el => {
this.coincapService
.getCoin(el.id)
.then((element) => {
currentCostArr.push(element.priceUsd * el.amount)
})
});
for (let i = 0; i < currentCostArr.length; i ) {
sum = currentCostArr[i];
}
console.log('cevf c ' sum)
console.log('current cost ' currentCostArr)
return currentCostArr;
}
getCoin method
getCoin = async (id) => {
const coin = await this.getResource(`/assets/${id}`);
return this._transformCoin(coin);
}
CodePudding user response:
The problem is that you are not handling correctly the Promise that .getCoin()
returns inside the .forEach()
'loop'. It's making multiple calls to getCoin
but the code outside the forEach
is not awaiting these multiple async calls, so the next lines will execute without awaiting the result of the Promises. This is causing confusion in execution order logic of your code, behaving different than what you are expecting. Actually the function getCurrentCost() is ending before the Promises inside the loop resolves.
One way to solve your problem is replacing the .forEach()
with .map()
, which will return several Promises that will be awaited will Promise.all()
, behaving the way it's expected.
//don't forget to turn the function async, so you can use await keyword.
async getCurrentCost() {
let sum = 0;
let existingEntries = JSON.parse(localStorage.getItem("walletData"));
if (existingEntries == null) existingEntries = [];
await Promise.all(existingEntries.map(async (el) => {
const coin = await this.coincapService.getCoin(el.id)
currentCostArr.push(coin.priceUsd * coin.amount)
})
return currentCostArr
}
CodePudding user response:
Your forEach
loop pushes values in you array asynchronously.
You calculate the sum before you get your array filled up with values.