Promises are handled using .then()
& .catch()
method.
These methods are called exactly when the promise
is either:
Remember this:
- Whenever a promise is resolved without any ERROR OR REJECTION, it will go in the .then method.
- If there are error, exception or rejection, it will go in the .catch method.
lets look at an example of a promise being resolved successfully.
const myPromise = new Promise((resolve, reject) => {
resolve("this will resolve this promise");
});
myPromise
.then((elem) => console.log("Promise resolved came in .then block"))
.catch((error) => console.log("promise with error came in .catch block ", error));
// prints
// this will resolve this promise
// Promise resolved came in .then block
example # 2:
Example of rejection:
// a rejected promise goes to .catch block
const myPromise = new Promise((resolve, reject) => {
reject("this will reject this promise");
});
myPromise
.then((elem) => console.log("Promise resolved came in .then block"))
.catch((error) => console.log("promise with error came in .catch block ", error));
// prints
// this will reject this promise
// promise with error came in .catch block
example # 3:
Example of Error:
// incase of error goes to .catch block
const myPromise = new Promise((resolve, reject) => {
throw "sample exception";
});
myPromise
.then((elem) => console.log("Promise resolved came in .then block"))
.catch((error) => console.log("promise with error came in .catch block ", error));
// prints
// promise with error came in .catch block
Hopefully, by now you understand the purpose of these blocks now. If any questions please let me know.