Sobes.tech
Junior — Middle

How can you organize the concurrent execution of multiple asynchronous operations?

sobes.tech AI

Answer from AI

In Node.js, there are several approaches to perform multiple asynchronous operations simultaneously:

  • Promise.all — takes an array of promises and returns a new promise that resolves when all the provided promises have resolved.
  • async/await with Promise.all for convenient syntax.
  • Modules like async with functions parallel or series.

Example with Promise.all:

async function fetchData() {
  const promise1 = fetch('https://api.example.com/data1');
  const promise2 = fetch('https://api.example.com/data2');

  const [response1, response2] = await Promise.all([promise1, promise2]);
  const data1 = await response1.json();
  const data2 = await response2.json();

  return { data1, data2 };
}

This approach allows running multiple asynchronous operations in parallel and waiting for their completion.