Promisify callbacks
Wrap a callback-style API by invoking resolve on success and reject on failure.
JavaScript · Class
Promise represents the eventual completion or failure of asynchronous work and its resulting value. It progresses from pending to fulfilled or rejected and supports handler-based chaining.
A Promise represents a value that may become available later or an operation that may fail. It starts pending and eventually becomes fulfilled or rejected; then(), catch(), and finally() attach work for those outcomes and return promises that enable chaining.
new Promise(executor)| Name | Type | Description |
|---|---|---|
executor | function | Function executed by the constructor; it receives resolveFunc and rejectFunc. |
A new Promise object.
const delayed = new Promise((resolve, reject) => {
setTimeout(() => resolve("done"), 10);
});
delayed
.then((value) => `${value}!`)
.catch((error) => `Failed: ${error}`)
.finally(() => console.log("settled"))
.then(console.log);This promise resolves asynchronously, then the chained handlers transform the fulfillment value, handle rejection if needed, and run cleanup after settlement.
Wrap a callback-style API by invoking resolve on success and reject on failure.
Sequence asynchronous operations while passing each result to the next handler.
Attach failure handling and cleanup to asynchronous operations.
A Promise is an object representing the eventual success or failure of an asynchronous operation. It begins pending and transitions to fulfilled with a value or rejected with a reason; handlers registered with then() run for the corresponding outcome.
Follow-up: What does then() return? It returns another Promise immediately, allowing the result of one asynchronous step to feed the next step in a chain.
The constructor receives an executor function, which is called with resolve and reject functions. Calling resolve supplies the outcome, while calling reject reports failure; an exception thrown by the executor also rejects the promise.
Follow-up: What happens if resolve receives a thenable? The promise can remain pending while it adopts that thenable's eventual state.
then() accepts up to two callbacks: one for fulfillment and one for rejection. catch() handles rejection, while finally() attaches cleanup that runs after the promise settles.
Follow-up: Why can these methods be chained? Each promise method produces or returns a promise, so later operations can consume the prior operation's result.
Promise()Promise.all()Promise.race()Promise.allSettled()Promise.any()Promise.prototype.then()Promise.prototype.catch()Promise.prototype.finally()