Skip to content Skip to sidebar Skip to footer

Async API Call Inside ForEach Loop

I ran into a problem that I cannot seem to solve, I'm guessing I'm missing some points in terms of async behaviour. The task is relatively simple: A wallet with money in different

Solution 1:

The problem is that async methods returns Promise and you need to wait them to resolve. The common pattern to do this is next:

Promise.all(arr.map(v => someAsyncFunc(v))).then((resolvedValues) => {
  resolvedValues.forEach((value) => {
    // Do your stuff here
  });
});

So basically you are initializing bunch of async calls, waiting for them to resolve with Promise.all and only after that preform some operations on resolved data.


Solution 2:

You should try something like this:

function fetchUrls(urlList) {
  let promises = [];
  for(idx in urlList) {
    promises.push(fetch(urlList[idx]));
  }
  return Promise.all(promises);
}

fetchUrls(your_list_of_urls)
.then(console.log)

Post a Comment for "Async API Call Inside ForEach Loop"