JavaScript path · Async · Topic 6 of 12

Promises

Not started

A promise stands for a result that isn't ready yet. It starts pending and settles exactly once, as fulfilled with a value or rejected with a reason. Callbacks given to then, catch and finally always run later as microtasks, even if the promise had already settled.

Why it matters: Nearly every modern API (fetch, file system, databases) hands back a promise. A rejection nobody handles is reported as an error in browsers and, by default, crashes a Node process.

1

How it works

The explanation, with examples you can run.

Always later

The function you pass to new Promise (the executor) runs immediately. Whatever you pass to then never does: it waits for the promise to settle and then for the current script to finish. That guarantee is what makes promise code predictable.

⌘/Ctrl + Enter
OutputNot run yet

Press Run to see what your code prints, in order.

Runs in this browser, in an isolated frame with no access to this page. console.log, info, warn and error are shown; code runs as a classic script, so use an async function for await.

Chains and errors

Every then returns a new promise, resolved with whatever its callback returns (or rejected with whatever it throws). An error skips the remaining then steps until it reaches a catch, much like try/catch in synchronous code. finally runs either way and passes the result through.

⌘/Ctrl + Enter
OutputNot run yet

Press Run to see what your code prints, in order.

Runs in this browser, in an isolated frame with no access to this page. console.log, info, warn and error are shown; code runs as a classic script, so use an async function for await.

Waiting for several

  • Promise.all: every input fulfilled, or the first rejection.
  • Promise.allSettled: waits for all of them and reports each outcome.
  • Promise.race: the first one to settle, either way.
  • Promise.any: the first one to fulfil; rejects only if all of them reject.
  • Promise.withResolvers() (ES2024) hands you a promise together with its resolve and reject, for when the code that settles it lives somewhere else.

An unhandled rejection is not silent: browsers log it and fire an unhandledrejection event, and Node (since version 15) ends the process by default. Always return or await the promises you create, and put a catch at the end of every chain.

2

Check yourself

2 questions. Get them all right to finish this topic.

  1. 1.What is printed second?
    const p = new Promise((resolve) => {  console.log("executor")  resolve(42)})p.then((v) => console.log("then", v))console.log("after")
  2. 2.Promise.all([a, b]) where a fulfils after 5 s and b rejects after 1 s. What happens?

0 of 2 right so far. Get all two to finish this topic.