Reputation: 247
I have an exercise to make a promise which ends with failure which returns the string "Failure". I have to use then to manipulate the error.
The problem is that my output is just the reason of the reject
and it doesn't even go to then
and it doesn't console.log
my string
My code:
const myPromise = new Promise((resolve, reject) => {
reject("failure").then(console.log("ended with failure"))
})
console.log(myPromise)
What have I done wrong?
Upvotes: 0
Views: 160
Reputation: 494
Promises are handled using .then()
& .catch()
method.
These methods are called exactly when the promise
is either:
Remember this:
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.
Upvotes: 2
Reputation: 2465
The right way to do that will be.
const myPromise = new Promise((resolve, reject) => {
reject("failure");
})
myPromise.catch(() => console.log("Caught an error!"));
resolve
and reject
are just functions that change the state of a promise, but not promises themself.
UPD: Please have look at this doc https://javascript.info/promise-basics it may help to learn promises.
Upvotes: 2