在 JavaScript 中使用 wait 时通过 catch 处理 Promise 拒绝

在 JavaScript 中,用户可以使用 Promise 执行特定操作。例如,我们可以创建使用 API 从数据库获取数据的 Promise。如果 Promise 成功从数据库获取数据,则意味着 Promise 成功,否则 Promise 出错,则意味着 Promise 被拒绝。
让我们先看看创建 Promise 的语法。
语法
用户可以按照以下语法在 JavaScript 中创建 Promise。
let testPromise = new Promise((res, rej) => {
// perform some operation
});
在上面的语法中,我们使用带有“new”关键字的 Promise() 构造函数来创建 Promise。
示例
在下面的示例中,我们创建了两个不同的 Promise。此外,我们已经解决并拒绝了它们。
用户可以在下面的代码中看到我们如何管理 testPromise1,因为它已成功解决。逻辑部分附带第二个承诺,即我们需要使用 catch 块来处理错误。在输出中,用户可以观察到 testPromise2 的 Promise 消息是从 catch 块中打印出来的。
<html>
<body>
<h2><i>Promise</i> in JavaScript</h2>
<p id = "output"> </p>
<script>
let output = document.getElementById("output");
// Creating the promise and resolving it
let testPromise1 = new Promise((res, rej) => {
res("The testPromise1 is resolved successfully!");
});
// rejecting the promise
let testPromise2 = new Promise((res, rej) => {
rej("The testPromise2 is Rejected due to error!");
});
// execute the testPromise1
testPromise1.then((res) => {
output.innerHTML += res;
output.innerHTML += "</br>";
});
//execute the testPromise2, and use the catch block to handle errors.
testPromise2
.then((res) => {
output.innerHTML += res;
})
.catch((error) => {
output.innerHTML += "Inside the catch block for testPromise2. </br>";
output.innerHTML += error;
});
</script>
</body>
</html>
将 Promise 与异步函数和await关键字结合使用
用户已经学会了创造承诺。此外,还学会了使用 catch 块处理已解决和已拒绝的承诺。
现在,我们将学习使用带有异步函数和await关键字的promise。因此,我们必须使用 try-catch 块来处理被拒绝的 Promise 中的错误。
异步函数允许我们在程序中并行执行多个任务。我们可以定义函数后跟async关键字以使其异步。之后,我们可以在函数内使用await关键字来等待promise结果。有时,如果没有从 Promise 中获得结果,我们就无法在函数中执行其他任务。因此,我们必须等待使用 await 关键字可以获得的结果。
语法
当我们使用带有await关键字的promise时,用户可以按照下面的语法使用try-catch块来处理promise错误。
async function executePromise() {
try {
// call the promise, and wait until it is fulfilled!
await promise1();
} catch (error) {
// if the promise is rejected, control comes here
}
}
在上面的语法中,我们使用 async 关键字使函数异步,并使用 await 关键字等待 Promise 被履行或拒绝。
示例
在下面的示例中,我们创建了异步函数。此外,我们还创建了 promise1() 函数,它返回一个带有拒绝的承诺。在异步函数中,我们使用await 关键字调用了promise1() 函数,并且当promise 被拒绝时,控制权转到catch 块。
<html>
<body>
<h3>Handling the <i>Promise rejection using catch block</i> While using await keyword in JavaScript.</h3>
<p id = "output"> </p>
<script>
let output = document.getElementById("output");
// rejecting the promise
let Promise1 = () => {
return new Promise((res, rej) => {
rej(new Error(400));
});
};
async function executePromise() {
try {
// call the promise, and wait until it is fulfilled!
await Promise1();
} catch (error) {
output.innerHTML += "Promise is rejected, and an error message is " + error.message;
}
}
executePromise();
</script>
</body>
</html>
示例
在下面的示例中,我们创建了与上面示例中创建的相同的 Promise,但是我们在拒绝 Promise 时添加了计时器。
当用户点击“execute Promise”按钮时,它会执行executePromise()函数。在executePromise()函数中,我们使用await关键字调用timerPromise(),并且timerPromise()拒绝承诺直到5秒,直到该函数等待继续前进。
<html>
<body>
<h3>Handling the <i>Promise rejection using catch block</i> While using await keyword and timer in JavaScript. </h3>
<p> Click on the "Execute promise" button and wiat for 5 seconds </p>
<p id = "output"> </p>
<button onClick = "executePromise()"> Execute promise </button>
<script>
let output = document.getElementById("output");
// rejecting the promise
let timerPromise = () => {
return new Promise((res, rej) => {
setTimeout(
() => rej(new Error("Promise is rejected after 5 seconds")), 5000
);
});
};
async function executePromise() {
try {
// function will not move ahead until the promise is fulfilled.
await timerPromise();
} catch (error) {
output.innerHTML += "Promise is rejected, and an error message is " + error.message;
}
}
</script>
</body>
</html>
在上面的输出中,用户可以观察到,当他们单击“执行 Promise”按钮时,5 秒后,他们会看到来自 catch 块的错误消息,因为 Promise 需要 5 秒才能被拒绝。
javascript