我正在学习 JavaScript 中的 Promise,我决定实现一个简单的 Promise,其中我将设置 3 秒的超时,然后拒绝该 Promise。拒绝它后,我捕获错误并将其显示在 HTML 元素中。该承诺完美运行并显示消息,但我在控制台中收到以下错误。
Uncaught (in promise) I hate you Promise.then (async) (anonymous)
这是供您参考的代码 -
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>
请帮助我找出我所犯的错误。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
这应该有效
<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>myPromise.then(function(value) { document.getElementById("demo").innerHTML = value; }).catch( error => { console.log("Catching it"); document.getElementById("demo").innerHTML = error; });您需要捕获 .then 之后的错误