JavaScript .then()

christian.dinh's avatar
Published Jul 27, 2021Updated Aug 29, 2023
Contribute to Docs

Returns a new Promise object.

  • A full-stack engineer can get a project done from start to finish, back-end to front-end.
    • Includes 51 Courses
    • With Professional Certification
    • Beginner Friendly.
      150 hours
  • Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.
    • Beginner Friendly.
      15 hours

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

All contributors

Contribute to Docs

Learn JavaScript on Codecademy

  • A full-stack engineer can get a project done from start to finish, back-end to front-end.
    • Includes 51 Courses
    • With Professional Certification
    • Beginner Friendly.
      150 hours
  • Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.
    • Beginner Friendly.
      15 hours