I am learning promises in javascript and I decided to implement a simple promise where I would set a timeout of 3 seconds and then reject the promise. Upon rejecting it, I am catching the error and displaying it in an HTML element. The promise works perfectly and displays the message, but I get the following error in the console.
Uncaught (in promise) I hate you
Promise.then (async)
(anonymous)
Here is the code for your reference –
const myPromise = new Promise(function(myResolve, reject) {
setTimeout(() => {
reject('I hate you');
}, 3000);
});
myPromise.then(function(value) {
document.getElementById("demo").innerHTML = value;
});
myPromise.catch( error => {
console.log("Catching it");
document.getElementById("demo").innerHTML = error;
});
<h2>JavaScript Promise</h2>
<p>Wait 3 seconds (3000 milliseconds) for this page to change.</p>
<h1 id="demo"></h1>
Please help me in finding out the error that I made.
3
Answers
This should work
You need to catch the error after .then
UPDATE
Thanks to the comment by tlvi38 on the accepted answer, I understand my query now, and the uncaught issue from the original question posted by the OP can be fixed by adding a separate
catch
block for the new promise returned by the unchainedthen
as following:ORIGINAL
Since I cannot add a comment, I am writing this as an answer, but I observed that other than the accepted answer, if you have just the
catch
block like following, it also works without any issue.But having both,
then
andcatch
not chained up, in any order givesUncaught error..
in console. Can someone explain why is that?