Promise
10 methodsRepresents the eventual result of an asynchronous operation. Core async primitive in JavaScript (ES6+).
Promise.all(iterable)Wait for all promises to fulfill. Rejects immediately if any promise rejects (fast-fail). Returns an array of results in input order.
Parameters
| Name | Type | Description |
|---|---|---|
| iterable | Iterable<Promise | non-Promise> | An iterable of promises (or values treated as already-resolved promises). |
Returns
Promise<Array>
Example
const [user, posts, comments] = await Promise.all([
fetchUser(1),
fetchPosts(1),
fetchComments(1),
]);
// If any fails, the whole thing rejects immediately.Promise.allSettled(iterable)Wait for all promises to settle (fulfill or reject). Never rejects — returns an array of { status, value } or { status, reason } objects. Useful when you want all results regardless of failures.
Parameters
| Name | Type | Description |
|---|---|---|
| iterable | Iterable<Promise | non-Promise> | An iterable of promises. |
Returns
Promise<Array<{ status: 'fulfilled', value } | { status: 'rejected', reason }>>
Example
const results = await Promise.allSettled([
fetch('/api/a'),
fetch('/api/b'),
fetch('/api/c'),
]);
results.forEach(r => {
if (r.status === 'fulfilled') console.log('OK:', r.value);
else console.log('Fail:', r.reason);
});Promise.any(iterable)Resolve with the first fulfilled promise. Rejects only if ALL promises reject (AggregateError). Useful for 'first successful response' patterns (e.g., racing CDNs).
Parameters
| Name | Type | Description |
|---|---|---|
| iterable | Iterable<Promise | non-Promise> | An iterable of promises. |
Returns
Promise<value>
Example
// Use the fastest-responding mirror
const fastest = await Promise.any([
fetch('https://mirror1.example.com/api'),
fetch('https://mirror2.example.com/api'),
fetch('https://mirror3.example.com/api'),
]);
// fastest is the response of the first one to succeed.Promise.race(iterable)Resolve or reject with the first promise to settle (fulfill OR reject). Useful for implementing timeouts. Unlike any(), a rejection also wins the race.
Parameters
| Name | Type | Description |
|---|---|---|
| iterable | Iterable<Promise | non-Promise> | An iterable of promises. |
Returns
Promise<value>
Example
// 5-second timeout
function withTimeout(promise, ms) {
return Promise.race([
promise,
new Promise((_, reject) =>
setTimeout(() => reject(new Error('timeout')), ms)
),
]);
}
const result = await withTimeout(fetch('/slow-api'), 5000);Promise.resolve(value)Create a promise that resolves immediately with the given value. If value is already a promise, it is returned as-is. Useful for converting non-promise values to promises or ensuring consistent async return types.
Parameters
| Name | Type | Description |
|---|---|---|
| value | any | Value to resolve with. If it's a thenable, follows it. |
Returns
Promise<value>
Example
// Ensure async return type
function getData(sync = false) {
if (sync) return Promise.resolve(cachedData);
return fetch('/api/data').then(r => r.json());
}
// Awaiting Promise.resolve(value) is a microtask:
await Promise.resolve(); // yields to the event loopPromise.reject(reason)Create a promise that rejects immediately with the given reason. Mostly used for testing or for explicit error signaling in promise chains.
Parameters
| Name | Type | Description |
|---|---|---|
| reason | any | Rejection reason (usually an Error object). |
Returns
Promise<never>
Example
// Validate before continuing
function requireAuth(user) {
if (!user) return Promise.reject(new Error('Unauthorized'));
return Promise.resolve(user);
}
try {
await requireAuth(null);
} catch (e) {
console.error(e.message); // 'Unauthorized'
}Promise.try(executor)since ES2025ES2025. Wrap a synchronous or asynchronous function call as a promise. Combines try/catch semantics with promise chaining — eliminates the dual try/catch + .catch() pattern. Falls back gracefully if not available.
Parameters
| Name | Type | Description |
|---|---|---|
| executor | () => value | Promise | Function to execute (sync or async). |
Returns
Promise<value>
Example
// Old way: dual try/catch + .catch
async function load() {
try {
const data = JSON.parse(raw); // sync throw
return await fetch('/save', { body: JSON.stringify(data) });
} catch (e) {
handle(e); // catches both
}
}
// New way: Promise.try handles both
Promise.try(() => JSON.parse(raw))
.then(data => fetch('/save', { body: JSON.stringify(data) }))
.catch(handle); // catches both sync and async errorspromise.then(onFulfilled, onRejected?)Register fulfillment and (optionally) rejection handlers. Returns a new promise, enabling chaining. If a handler returns a value, the new promise resolves with it; if it returns a promise, the new promise adopts its state.
Parameters
| Name | Type | Description |
|---|---|---|
| onFulfilled | (value) => result | Promise | Callback run when the promise fulfills. |
| onRejected | (reason) => result | Promise | Optional. Callback run when the promise rejects (acts like catch). |
Returns
Promise<result>
Example
// Chaining with value transformation
fetch('/api/user/1')
.then(r => r.json()) // Promise resolves with parsed JSON
.then(user => user.name) // Resolves with the name string
.then(name => `Hello, ${name}`)
.then(greeting => console.log(greeting));promise.catch(onRejected)Register a rejection handler. Returns a new promise. If onRejected returns a value (or doesn't throw), the new promise RESOLVES (recovery), so catch can be used to recover from errors mid-chain.
Parameters
| Name | Type | Description |
|---|---|---|
| onRejected | (reason) => result | Promise | Callback run when the promise rejects. |
Returns
Promise<result>
Example
// Recovery: catch returns a value, so the chain continues
fetch('/api/primary')
.catch(() => fetch('/api/fallback')) // try fallback
.then(r => r.json())
.then(data => render(data));
// Without recovery (just log):
promise.catch(err => console.error('failed:', err));promise.finally(onFinally)Register a handler that runs regardless of fulfillment or rejection. The returned promise mirrors the original's state. onFinally cannot inspect the value or reason, and any value it returns is ignored. Useful for cleanup.
Parameters
| Name | Type | Description |
|---|---|---|
| onFinally | () => void | Callback run when the promise settles. |
Returns
Promise<value>
Example
// Show/hide loading spinner regardless of outcome
button.disabled = true;
showSpinner();
fetch('/api/save', { method: 'POST', body: data })
.then(r => showToast('Saved!'))
.catch(e => showToast('Error: ' + e.message))
.finally(() => {
button.disabled = false;
hideSpinner();
});