.then()

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.

Code
Output
Loading...

All contributors

Contribute to Docs

Learn JavaScript on Codecademy