Promise
An object representing the result of an operation that will be available in the future: a value on success or an error.
- Returns
- A new
Promiseobject in the pending state.
Example
#const promise = new Promise((resolve) => {
console.log('1. Executor starts immediately')
setTimeout(() => resolve('3. Result after 300 ms'), 300)
})
promise.then((value) => console.log(value))
console.log('2. Code after creating the promise')Definition and usage
#A promise (Promise) is an object that stands in for the result of an operation that isn’t ready yet, such as fetching data from a server. It starts in the pending state (pending), then permanently moves into one of two states: fulfilled (fulfilled) with a value, or rejected (rejected) with a reason.
The new Promise(executor) constructor takes a function that receives two other functions: resolve to report success and reject to report an error. The executor function runs immediately, synchronously, the moment the promise is created. You react to the result with the then(), catch(), and finally() methods, or with the await keyword.
A promise settles only once. Further calls to resolve or reject are ignored. Functions passed to then() always run asynchronously, even when the promise is already fulfilled, so code written after them runs first.
In practice, you rarely create promises by hand. Built-in APIs such as fetch() return them, and so does every async function. The constructor is mostly useful for wrapping older callback-based code, such as setTimeout().
Syntax
#new Promise((resolve, reject) => { … })Parameters
#executor
function (resolve, reject)
The function that runs immediately when the promise is created. Callresolve(value)inside it on success, orreject(error)on failure.
More examples
#const checkAnswer = (answer) =>
new Promise((resolve, reject) => {
setTimeout(() => {
if (answer === 42) resolve('Correct answer!')
else reject(new Error('Try again'))
}, 200)
})
console.log('Checking...')
checkAnswer(42).then((message) => console.log(message))
checkAnswer(7).catch((error) => console.log(error.message))const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
console.log('Loading the level...')
await wait(500)
console.log('Level loaded')const promise = new Promise((resolve, reject) => {
resolve('first result')
resolve('second result')
reject(new Error('too late'))
})
promise.then((value) => console.log(value))Browser support
#Widely available
Works in all modern browsers, phones included. You can use it without worry.
- Chrome
- Edge
- Firefox
- Safari
Good practices
#- Always handle a promise’s error with
catch()ortry...catchwithawait. An unhandled rejection shows up in the console as an "Uncaught (in promise)" error. - Pass an
Errorobject toreject(), not a plain string. That way you get a message inmessage, an error name, and a call stack. - Instead of long
then()chains, new code is usually more readable withasyncandawait.
Related entries
#- Promise.prototype.then()Registers a function to run when the promise is fulfilled, and returns a new promise so you can chain steps together.
- Promise.prototype.catch()Registers an error-handling function that runs when the promise is rejected.
- async functionDeclares an asynchronous function that always returns a promise and can use the await keyword inside it.
- awaitPauses an async function until a promise settles, then returns its value or throws its error.
- Promise.all()Waits for every promise to be fulfilled and returns an array of their results. Rejects at the first error.
- setTimeout()Runs a function once, after the given number of milliseconds has passed.
Spotted a mistake or missing an example? Write to us.