LESSON 57 · INTERMEDIATE4 min read

Promises & Combinators

Represent asynchronous results as values, chain work without nesting, and coordinate several operations with the built-in combinators.

ES2024 / Node.js 20+Free to readModule 13 of 19
YOUR NEXT SMALL WINS

By the end, you’ll be able to…

  • Describe the pending, fulfilled, and rejected states of a promise.
  • Chain promise handlers and propagate errors to a single catch.
  • Choose between Promise.all, allSettled, race, and any for a given task.

01A promise is a placeholder for one outcome

A promise is an object that represents the eventual result of an asynchronous operation. It starts pending, then becomes fulfilled with a value or rejected with a reason. Once settled, it never changes again, so every handler attached later observes the same outcome. The function passed to the constructor runs immediately; resolve and reject settle the promise.

Promises move callbacks out of the function that starts the work. Instead of passing a callback into loadUser, you receive a value that can be stored, returned, and combined. Handlers always run asynchronously, even when the promise is already fulfilled, which keeps ordering predictable.

Promise.resolve(value) creates a fulfilled promise, and Promise.reject(reason) creates a rejected one. Both are useful in tests and in functions that sometimes return a cached value synchronously. A plain value returned from a handler is also wrapped automatically, so the next link does not need to care which form it received.

promise-basics.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.

02Chaining flattens the pyramid

then returns a new promise, which is what makes chaining work. Whatever you return becomes the fulfillment value of the next link; if you return another promise, the chain waits for it and adopts its result. Throwing inside a handler rejects the next link, so one catch at the end can handle failures from any earlier step.

Return the promise instead of nesting another then call. Nesting recreates callback hell with extra steps and hides errors from the outer chain. finally is for cleanup that must run on both success and failure, such as clearing a timer or hiding a spinner; it does not change the value unless it throws.

chaining.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.

03Combinators coordinate many promises

Combinators accept an iterable of promises and return one promise. Promise.all fulfills with an array of values in input order, or rejects as soon as any input rejects. Promise.allSettled waits for every input and returns objects with status fulfilled or rejected, which suits dashboards where one failed widget should not hide the rest.

Promise.race settles with the first input to settle, whether it succeeds or fails. Promise.any ignores rejections and fulfills with the first success, throwing an AggregateError only if every input fails. Choose according to whether you need every result, every outcome, the first signal, or the first success.

combinators.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.

04Timeouts and clean-up

A timeout is a race between the real operation and a timer that rejects. Clear the timer in finally so a fast success does not leave a pending callback. This pattern works with any promise, not just network calls, which is why it belongs in your toolkit before you meet fetch.

Two habits prevent most promise bugs: always return a promise from a then handler if the next step depends on it, and attach a rejection handler to every chain you start. A floating promise with no catch becomes an unhandled rejection and can terminate a modern Node.js process.

Combinators also accept plain values, which are wrapped as already-fulfilled promises. That makes it safe to build a list containing a cached value and a live request. If you need to map over items, Promise.all(items.map(loadItem)) is the common shape; use allSettled when a single bad item should not reject the whole batch.

timeout.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.
LET IT CLICK

The ideas worth keeping.

  • A promise settles once, and every handler sees the same fulfillment value or rejection reason.
  • Return values from then to flatten chains; one catch can handle any earlier failure.
  • Use all for every result, allSettled for every outcome, race for the first signal, and any for the first success.
TURN UNDERSTANDING INTO SOMETHING YOU CAN DO

Make it yours.

Type and test your code right here in the interactive workspace. Run your solution, check the output, and compare with the worked guide when ready.

01

Exercise 1: Flatten a nested chain

Rewrite this sequence as a single promise chain: load a user, pass the user id to loadOrders, then log how many orders were returned. Handle any failure with one catch.

your_turn_1.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.
Explore a worked solution
one_possible_solution.jsJavaScript
function getUser() {  return Promise.resolve({ id: 7, name: "Ada" });}function getOrders(userId) {  return Promise.resolve([{ id: 1 }, { id: 2 }]);}getUser()  .then((user) => getOrders(user.id))  .then((orders) => console.log(`${orders.length} orders`))  .catch((error) => console.error(error.message));

Returning getOrders from the first handler makes the chain wait for the second promise and adopt its array. Errors from either step skip the success handlers and reach the single catch. The output is 2 orders.

02

Exercise 2: Report every outcome

Given three tasks where one rejects, use Promise.allSettled to wait for all of them and print a summary that keeps the successful values and the failure message.

your_turn_2.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.
Explore a worked solution
one_possible_solution.jsJavaScript
const tasks = [  Promise.resolve("saved"),  Promise.reject(new Error("offline")),  Promise.resolve("queued"),];const results = await Promise.allSettled(tasks);const summary = results.map((result) =>  result.status === "fulfilled"    ? result.value    : `failed: ${result.reason.message}`);console.log(summary.join(", "));

allSettled never rejects because of an input rejection; it records each outcome in input order. The summary is saved, failed: offline, queued, so one failure does not discard the successful results.

A SMALL QUESTION. A USEFUL NEXT STEP.

What stayed with you?

Check the ideas while they’re fresh. Your answers stay in this page and feedback appears as you go.

A LITTLE ACTIVE RECALL0 / 3 answered
01How does Promise.all behave when the second of four promises rejects?
02What happens when a then handler returns a promise?
03When is finally the right place to hide a loading indicator?
⚡CODING CHALLENGE
🔒Required to Mark Lesson Complete

Exercise 1: Flatten a nested chain

Rewrite this sequence as a single promise chain: load a user, pass the user id to loadOrders, then log how many orders were returned. Handle any failure with one catch.

EXPECTED OUTPUT
[Process exited with code 0 - No output]
main.jsJavaScript
Ctrl + ↵
Execution Console
Click "Run & Verify" (or press Ctrl + Enter) to test your code against the challenge.

Keep exploring.

The official references behind this lesson, when you want a second angle or the full details.

One lesson closer.

Reading is a start. Trying it yourself makes the connection.

Solve the hands-on coding challenge in the knowledge section to verify your code and unlock lesson completion.