🎓 A1Learner
🔍
0 of 50 lessons completed

Promise Methods

Promise methods combine promises into one new promise. Each method waits in its own way.

A helper that finishes later

This helper returns a promise that resolves with a value after a wait.

function after(value, ms) {
  return new Promise((resolve) => {
    setTimeout(() => resolve(value), ms);
  });
}

The first to finish

Fast finishes first, so race gives back Fast.

Promise.race([after("Slow", 200), after("Fast", 50)]).then((value) => {
  console.log(value);
});

Waiting for every result

This waits for both promises. The last line reads each status.

const good = Promise.resolve("OK");
const bad = Promise.reject(new Error("Nope"));
Promise.allSettled([good, bad]).then((results) => {
  console.log(results.map((result) => result.status));
});

The first success

This gives back OK, the first fulfilled value.

Promise.any([bad, good]).then((value) => {
  console.log(value);
});

Example

function after(value, ms) {
  return new Promise((resolve) => {
    setTimeout(() => resolve(value), ms);
  });
}

Promise.all([after("A", 100), after("B", 50)]).then((values) => {
  console.log(values);
});

Key points

  • Promise.all waits for every promise to fulfill.
  • Promise.all gives back the values in order.
  • Promise.all rejects as soon as one promise rejects.
  • Promise.race gives back the first finished value.
  • Promise.allSettled waits for every promise to settle.
  • Settle means fulfill or reject.
  • Promise.allSettled never rejects.
  • Promise.any gives back the first fulfilled value.

In this example, after returns a promise for each value. The first promise resolves with A after a longer wait. The second promise resolves with B after a shorter wait. Promise.all waits for both and prints the values in order.

Note

Promise.any rejects only when every promise rejects.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does Promise.all return?