Sobes.tech
Middle

What is the difference between Promise and async/await? How to perform two asynchronous requests in parallel? What Promise methods do you know (all, allSettled, race, any)?

sobes.tech AI

Answer from AI

Promise is an object representing the result of an asynchronous operation, which can either succeed or fail. async/await is syntactic sugar over Promise, allowing you to write asynchronous code in a synchronous style, improving readability.

Difference:

  • Promise requires the use of .then() and .catch() methods to handle the result.
  • async/await allows using the await keyword to wait for the Promise result inside an async function.

To perform two asynchronous requests in parallel, Promise.all is used, which takes an array of promises and returns a new promise that resolves when all the original promises are fulfilled.

Example of parallel requests:

async function fetchData() {
  const [res1, res2] = await Promise.all([
    fetch('/api/data1'),
    fetch('/api/data2')
  ]);
  const data1 = await res1.json();
  const data2 = await res2.json();
  return { data1, data2 };
}

Main Promise methods:

  • Promise.all(iterable) — waits for all promises to fulfill; if one rejects, the entire promise rejects.
  • Promise.allSettled(iterable) — waits for all promises to settle, returns an array of their statuses and results, does not reject.
  • Promise.race(iterable) — returns the result of the first settled promise (fulfilled or rejected).
  • Promise.any(iterable) — returns the result of the first fulfilled promise; if all are rejected, it rejects with an AggregateError.