Promise
A promise of a result that will be ready later: success or failure.
Available since: ES2015
Syntax
new Promise(executor)Parameters
| Parameter | Type | Description |
|---|---|---|
| executor | Function | A function that starts the work and calls resolve(value) on success or reject(error) on failure. |
Return value
PromiseAn object promising a result that arrives later.
Examples
A promise that resolves after 100 ms:
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
await delay(100);
console.log('100 ms later');Output:
100 ms laterSuccess and failure:
function checkAge(age) {
return new Promise((resolve, reject) => {
if (age >= 18) resolve('Access granted');
else reject(new Error('Too young'));
});
}
checkAge(20).then((message) => console.log(message));
checkAge(15).catch((error) => console.log(error.message));Output:
Access granted
Too youngNotes
A promise has three states: pending, fulfilled and rejected. The state changes only once: further calls to resolve and reject are ignored.
You rarely create promises yourself — usually ready-made functions such as fetch() return them. The easiest way to get the result is await.
See also
- Promise.prototype.then — Says what to do with a promise's result.
- async function — A function that always returns a promise and lets you use await inside.
- await — Waits for a promise and returns its value.
- Promise.all — Waits for all promises in parallel.
Related recipes
In the tutorial
- Promises — Promises in JavaScript: promise states, then, catch, finally, creating a promise with new Promise, and chains.