Files
developer-roadmap/src/data/question-groups/javascript/content/error-in-promise.md
T
Arik Chakma abbeb717d1 Add JavaScript questions (#4505)
* Add Javascript questions

* wip: add more questions

* wip: add ternary operator

* wip: add more questions

* wip: add more questions

* wip: add more questions

* wip: add more questions

* fix: set example

* wip: add more questions

* wip: add more question

* wip: add more questions

* wip: add more questions

* wip: add more questions

* wip: add more questions

* wip: add more questions

* wip: add more questions

* wip: add more questions

* wip: add another question

* wip: add more questions

* wip: add more questions

* wip: add more questions

* wip: add more questions

* wip: add more questions

* wip: add more questions

* wip: add more questions

* wip: add more questions
2023-10-12 15:03:19 +01:00

858 B

In order to handle errors in promises, we can use the catch method or the second argument of the then method.

Rejecting a promise

const promise = new Promise((resolve, reject) => {
  reject(new Error('Something went wrong'));
});

Catch method

In this method, we can pass a callback function that will be called when the promise is rejected.

promise
  .then((result) => {
    console.log(result);
  })
  .catch((error) => {
    console.log(error.message);
  });

Second argument of the then method

In this method, we can pass two callback functions as arguments. The first one will be called when the promise is resolved and the second one will be called when the promise is rejected.

promise.then(
  (result) => {
    console.log(result);
  },
  (error) => {
    console.log(error.message);
  }
);