ES6+ (Modern JavaScript) · Structure

Promises

A promise is an IOU for a value that will arrive later. The basics are in the JavaScript track; here you will master the combinators that run several async tasks at once.

Intermediate 5 min Lesson 12 of 23 Runnable examples
0/23 in ES6+
On this page · 5 min · Intermediate

Learning objectives#

  • Wrap callback code in a promise
  • Chain then, catch and finally
  • Run tasks in parallel with Promise.all
  • Choose between all, allSettled, race and any

Explanation#

new Promise((resolve, reject) => …) wraps any async work. Call resolve(value) on success, reject(error) on failure. A promise settles only once.

Promise.all([p1, p2]) waits for all to succeed and gives an array of results in order. If any one fails, the whole thing fails immediately.

Promise.allSettled waits for all to finish and reports each one as { status: "fulfilled", value } or { status: "rejected", reason } — it never fails.

Promise.race settles with whichever finishes first (success or failure) — useful for timeouts. Promise.any resolves with the first success and fails only if all fail.

Syntax#

JavaScript Illustrative
Promise.all([a, b]).then(([ra, rb]) => …);
Promise.allSettled([a, b]).then(results => …);
Promise.race([task, timeout]);
Promise.any([mirror1, mirror2]);

Code example: The four combinators#

JavaScriptThe four combinators Runnable
const wait = (ms, value, fail = false) =>
  new Promise((resolve, reject) =>
    setTimeout(() => (fail ? reject(new Error(value)) : resolve(value)), ms));


Promise.all([wait(100, 'user'), wait(50, 'orders')])
  .then(results => console.log('all:', results));


Promise.allSettled([wait(30, 'ok'), wait(20, 'boom', true)])
  .then(results => console.log('allSettled:', results.map(r => r.status)));


Promise.race([wait(80, 'slow'), wait(10, 'fast')])
  .then(winner => console.log('race:', winner));


Promise.any([wait(40, 'a', true), wait(60, 'b')])
  .then(first => console.log('any:', first));
Expected output
race: fast
allSettled: [ 'fulfilled', 'rejected' ]
any: b
all: [ 'user', 'orders' ]
Opens this example in the full playground

Step-by-step explanation#

  1. wait() turns setTimeout into a promise that resolves or rejects after ms milliseconds.
  2. race finishes first (10 ms) with the fastest value.
  3. allSettled finishes at 30 ms and reports one success and one failure without throwing.
  4. any ignores the failure at 40 ms and resolves with "b" at 60 ms.
  5. all waits for the slowest (100 ms); results keep the input order, not finishing order.

Real-world use case#

A dashboard loads user, orders and notifications in parallel with Promise.all; a fetch with a 5-second limit uses Promise.race against a timeout promise.

Common mistakes#

Using all when partial failure is OK

One failed widget should not blank the whole dashboard. Use allSettled and show what succeeded.

Forgetting to return inside then

.then(() => { fetchNext(); }) does not wait for fetchNext. Return the promise: .then(() => fetchNext()).

No catch at the end

An unhandled rejection is logged as an error and may crash Node.js. End chains with .catch().

Best practices#

  • Start independent tasks together and await them with Promise.all
  • Use allSettled for “best effort” work
  • Add a timeout with race for slow network calls
  • Always handle rejections

Remember this#

all = everyone must succeed. allSettled = tell me how everyone did.

race = first to finish (win or lose). any = first to succeed.

Results from all come back in the order you asked, not the order they finished.

Practice exercise#

Your task: Write timeout(promise, ms) that rejects with "Timed out" if the promise takes longer than ms.

Need a hint?
Race the promise against a new promise that rejects after ms.
Show solution
JavaScript Runnable
const timeout = (promise, ms) =>
  Promise.race([promise, new Promise((_, reject) => setTimeout(() => reject(new Error('Timed out')), ms))]);


const slow = new Promise(r => setTimeout(() => r('done'), 500));
timeout(slow, 100).then(console.log).catch(e => console.log(e.message)); // Timed out
Opens this example in the full playground

Mini quiz#

Promises quizMultiple choice Question 1 of 3

Which combinator never rejects, reporting each result instead?

Score so far: 0/0

Want more? Practise all ES6+ MCQs · ES6+ interview questions

My notes#

Saved in this browser.

Progress is saved in this browser. Sign in to sync.