I have the following code,
let currencyValues = [];
const retrieveCurrencyPairs = async (pair) => {
const r = await fetch(pair.url);
const rParsed = await r.json();
let newCurrencyValue = { currency: pair.countries, value: rParsed };
return newCurrencyValue;
};
useEffect(() => {
currencyValues = currencyPairs.map(retrieveCurrencyPairs);
console.log(currencyValues);
}, []);
and the following expectations:
useEffect
triggers the function inside of the map()retrieveCurrencyPairs()
is triggered and awaits for the result, which is then returnedcurrencyValues
array is the filled with the 3 new objectsUnfortunately the function is returning promises, instead of the objects.
Any tip on how to return the objects instead?
async functions always return promises. You could do this instead:
Promise.all(currencyPairs.map(retrieveCurrencyPairs))
.then( results => ... )
Promise.all has the additional benefit of running them all in parallel instead of sequentially.
You might consider Promise.allSettled if you want to deal with individual failures/rejections without rejecting the whole list.