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.
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.
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 itsresolveandreject, 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.
Check yourself
2 questions. Get them all right to finish this topic.
0 of 2 right so far. Get all two to finish this topic.