Skip to content

Promises

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');
});

.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'); });
CombinatorBehavior
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

The snippet creates two Promises that resolve immediately with fixed values, chains .then, uses Promise.all, and adds .finally for cleanup.

JavaScript

The output is always: Fetched: data-A, then All done: data-A and data-B, then Finally: cleanup.

Which Promise state means the operation completed successfully?
What does Promise.all do when one of the input Promises rejects?
Which combinator resolves when ALL input Promises settle, and never rejects?