Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

why .then() is getting called twice in promises {javascript}

Problem: last 2 .then are getting called even while i am returning Promise.reject().

1st .then() is printing undefined and 2nd .then() is also printing the output

can someone please explain why?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

let p4 = new Promise((resolve,reject)=>{
    resolve("p4 Resolved");
    });

p4.then((val)=>{
    console.log(val);
    return Promise.reject("20 Rejected"); }
    )
    .catch((error)=>{console.log(error)})
    .then((val)=>{console.log(val);return 290})
    .then((val)=>{console.log("Last then : "+val);})
    ;

>Solution :

catch also returns a promise and since you didn’t return anything, it will be a promise that fulfills to undefined, therefore the first then prints undefined. Finally, the last then gets the value 290 from the previously returned promise by the first then and prints it.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading