Search code examples
javascripthtmlcssasynchronouses6-promise

Uncaught (In Promise) error while using setTimeout() to Reject a promise in JavaScript


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.


Solution

  • myPromise.then(function(value) {
      document.getElementById("demo").innerHTML = value;
    }).catch( error => {
        console.log("Catching it");
        document.getElementById("demo").innerHTML = error;
    });
    

    You need to catch the error after .then