How to run multiple asynchronous tasks and wait until they've completed before executing the remaining code

Posted: 06-10-2022 | Views: 106
How to run multiple asynchronous tasks and wait until they've completed before executing the remaining code

When you need to run an asynchronous operation for each element in an array, you might naturally reach out for the .forEach() method.

For instance, you might have an array of todo IDs and for each todo ID, you want to fetch the todo and push the todo to an array. At the end, you log the todos, but alas, the array is empty.

const todoIdList = [1, 2, 3];
const todos = [];

async function fetchTodoById(id) {
  const res = await fetch('https://jsonplaceholder.typicode.com/todos/' + id);
  const todo = await res.json();
  return todo;
}

todoIdList.forEach(async (id) => {
  const todo = await fetchTodoById(id);
  todos.push(todo);
});

console.log('forEach todos', todos);

The solution is to map each element of an array to a promise, and pass the resulting array of promises to Promise.all. We have to use Promise.all because the await keyword only works on a single promise.

const todoIdList = [1, 2, 3];
const todos = [];

async function fetchTodoById(id) {
  const res = await fetch('https://jsonplaceholder.typicode.com/todos/' + id);
  const todo = await res.json();
  return todo;
}

const promises = todoIdList.map(async (id) => {
  const todo = await fetchTodoById(id);
  return todo;
});

Promise.all(promises).then(res => {
  todos.concat(res)
  console.log('Promise all todos', todos)
});

Add comment