.then()

Anonymous contributor's avatar
Anonymous contributor
Anonymous contributor's avatar
Anonymous contributor
Published Jul 27, 2021Updated Aug 29, 2023
Contribute to Docs

Returns a new Promise object.

Syntax

Promise.prototype.then(resolvedPromiseCallback, rejectedPromiseCallback);

The resolvedPromiseCallback function handles any resolved data from the previously fulfilled promise. The other argument, rejectedPromiseCallback, is optional and executes if the previous Promise was rejected.

Example

const myPromise = new Promise((resolve, reject) => {
if (2 + 2 === 3) {
resolve('Success!');
} else {
reject({
errorType: 'ArithmeticError',
message: "The numbers don't add up!",
});
}
});
myPromise.then(
(result) => {
console.log(result);
},
(reason) => {
console.log(`${reason.errorType}: ${reason.message}`); // ArithmeticError: The numbers don't add up!
}
);

Codebyte Example

The following example shows a .then() method executed for a successful result only by passing the resolve argument as the callback function.

us
Visit us
code
Hide code
Code
Output
Hide output
Hide output
Loading...

All contributors

Looking to contribute?

Learn JavaScript on Codecademy