Module 8: Asynchronous JavaScript
Promises: then, catch, and finally
Represent eventual success or failure and compose asynchronous steps.
A promise represents the eventual result of an asynchronous operation. It begins pending and settles as fulfilled or rejected. Attach handlers with .then, .catch, and .finally.
Promise.resolve(5)
.then(value => value * 2)
.then(value => console.log(value))
.catch(error => console.error("Operation failed", error))
.finally(() => console.log("Finished"));
A value returned from a .then callback becomes the value of the next promise in the chain. If the callback returns another promise, the chain waits for it. If a callback throws, the chain becomes rejected unless a later handler recovers.
Promise creation#
const delayedValue = new Promise((resolve) => {
setTimeout(() => resolve("Ready"), 300);
});
The executor passed to new Promise runs immediately. Usually, consume promises returned by APIs rather than wrapping them unnecessarily in a new promise; this avoids the common Promise constructor antipattern.
Run operations together#
Promise.all fulfills when every input fulfills and rejects as soon as one input rejects. Promise.allSettled waits for all inputs and reports each outcome. Promise.race settles with the first settled input; Promise.any fulfills with the first fulfilled input or rejects if all reject.
Practice#
Use Promise.all to await two independent promise-returning functions and combine their results. Add a catch handler that gives a meaningful failure message.