Uncaught (In Promise) error when rejecting a Promise using setTimeout() in JavaScript
P粉139351297
2023-09-05 17:39:46
<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>
This should work
You need to catch the error after .then