Promises
What is a Promise?
Section titled “What is a Promise?”A Promise is an object representing a value that will be available in the future. It has three states:
- Pending — the operation is still in progress.
- Fulfilled — the operation completed successfully; the Promise holds a value.
- Rejected — the operation failed; the Promise holds an error.
A Promise transitions from pending to either fulfilled or rejected — never back. Once settled, it stays that way.
var p = new Promise(function(resolve, reject) { // Call resolve(value) to fulfill, or reject(error) to reject resolve('hello');});Chaining with .then / .catch / .finally
Section titled “Chaining with .then / .catch / .finally”.then(onFulfilled) returns a new Promise, allowing you to chain steps. .catch(onRejected) handles rejections. .finally(fn) runs regardless of outcome — useful for cleanup.
fetchData() .then(function(data) { return process(data); }) .then(function(result) { console.log('Done:', result); }) .catch(function(err) { console.error('Failed:', err.message); }) .finally(function() { console.log('Cleanup'); });Promise combinators
Section titled “Promise combinators”| Combinator | Behavior |
|---|---|
Promise.all(arr) | Resolves when all resolve; rejects on the first rejection |
Promise.race(arr) | Settles with the first Promise to settle (fulfilled or rejected) |
Promise.allSettled(arr) | Resolves when all settle; gives each outcome (never rejects) |
Promise.any(arr) | Resolves with the first fulfilled; rejects only if all reject |
Runnable demo
Section titled “Runnable demo”The snippet creates two Promises that resolve immediately with fixed values, chains .then, uses Promise.all, and adds .finally for cleanup.
The output is always: Fetched: data-A, then All done: data-A and data-B, then Finally: cleanup.