I'm trying to call a function in loop and function doing some https request the response is returning back to function and it returns :
{"_U": 0, "_V": 0, "_W": null, "_X": null}
I want to return the exact value to that key where the function is called in the loop.
Here is my code :
res.forEach(async (elem, index) => {
await arr.push({
id: index,
name: '',
color: '#2F14A8',
chain: elem.chain,
address: elem.walletAddress,
balance: getWalletBalance(elem.walletAddress), //<---- **function call**
img: images[index % images.length],
});
});
Here is the function :
const getWalletBalance =async address => {
let tokensArr=[] // some arry
const res = await dispatch(getBalanc(address, tokensArr));
return res;
}
CodePudding user response:
What is the response for res in getWallertBalance
function?
I think if u put await before getWalletBalance(elem.walletAddress)
in forEach solves the problem!
CodePudding user response:
Those individual calls to getWalletBalance
don't appear to depend on each other. The best way to do this is to produce a collection of promises with map
, the resolve them concurrently...
const getWalletBalance = async address => {
const res = await dispatch(getBalanc(address, tokensArr));
const promises = res.map(element => getWalletBalance(elem.walletAddress));
const balances = await Promise.all(promises);
return res.map((element, index) => {
return {
id: index,
name: '',
color: '#2F14A8',
chain: element.chain,
address: element.walletAddress,
balance: balances[i],
img: images[index % images.length],
};
})
}