To use async/await usually doesn't work in a forEach loop, you need to use a for...of loop instead, or await Promise.all, to actually run async code in parallel.
for async(let item of items) {
await doSomethingWith(item)
}
const promises = [1, 2, 3].map(n => Promise.resolve(n*1000)) // 1
const promisesPromise = Promise.resolve(promises) // 2
// you can't do async at the toplevel, so we need to put it in an iife***(Immediately Invoked Function Expression https://dev.to/gyi2521/what-is-iife-in-javascript-o81)
void async function() {
console.log("===== for-of =====")
// 1 2
for await (const val of await promisesPromise)
console.log(val)
console.log("===== forEach =====")
;(await promisesPromise) // wait for 2
.forEach(async val => console.log(await val)) // wait for 1
}()
check the below screenshot
https://cl.ly/70a80d88dd7d
or follow this code,
const promises = transactionsData.map(async trans => {
const { destination } = trans;
const destinationUser = await fetch(`/api/v1/users/${destination}`);
const destinationUserData = await destinationUser.json();
return {
...trans,
destinationName: destinationUserData.user.full_name
};
});
const finalTransactions = await Promise.all(promises);