search

Home  >  Q&A  >  body text

Uncaught (In Promise) error when rejecting a Promise using setTimeout() in JavaScript

<p>I'm 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. After rejecting it, I catch the error and display it in an HTML element. The promise runs perfectly and displays the message, but I get the following error in the console. </p> <pre class="brush:php;toolbar:false;">Uncaught (in promise) I hate you Promise.then (async) (anonymous)</pre> <p>Here is the code for your reference -</p> <p> <pre class="snippet-code-js lang-js prettyprint-override"><code>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; });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code><h2>JavaScript Promise</h2> <p>Wait 3 seconds (3000 milliseconds) for this page to change.</p> <h1 id="demo"></h1></code></pre> </p> <p>Please help me figure out the mistake I'm making. </p>
P粉139351297P粉139351297515 days ago527

reply all(2)I'll reply

  • P粉748218846

    P粉7482188462023-09-06 12:09:35

    This should work

    <html>
    
    <body>
    
      <h2>JavaScript Promise</h2>
    
      <p>Wait 3 seconds (3000 milliseconds) for this page to change.</p>
    
      <h1 id="demo"></h1>
    
      <script>
        const myPromise = new Promise(function(myResolve, reject) {
          setTimeout(() => {
            reject('I hate you');
          }, 3000);
        });
    
        myPromise.then(function(value) {
          document.getElementById("demo").innerHTML = value;
        }).catch(error => {
          console.log("Catching it");
          document.getElementById("demo").innerHTML = error;
        });
      </script>
    
    </body>
    
    </html>

    reply
    0
  • P粉696891871

    P粉6968918712023-09-06 10:15:51

    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

    reply
    0
  • Cancelreply