使用await时用catch处理Promise拒绝
在JavaScript中,用户可以使用Promise执行特定操作。例如,我们可以创建Promise来使用API从数据库中获取数据。如果Promise成功从数据库获取数据,则表示Promise成功;如果Promise出现错误,则表示Promise被拒绝。
让我们先看看创建Promise的语法。
语法
用户可以按照以下语法在JavaScript中创建Promise。
let testPromise = new Promise((res, rej) => { // perform some operation });
在上面的语法中,我们使用了`Promise()`构造函数和`new`关键字来创建一个Promise。
示例
在下面的示例中,我们创建了两个不同的Promise。此外,我们还解决了并拒绝了它们。
用户可以在下面的代码中看到我们如何管理`testPromise1`,因为它已成功解决。逻辑部分包含第二个Promise,我们需要使用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关键字一起使用
用户已经学习了如何创建Promise。还学习了如何使用catch块处理已解决和已拒绝的Promise。
现在,我们将学习如何将Promise与异步函数和await关键字一起使用。因此,我们必须使用try-catch块来处理来自已拒绝Promise的错误。
异步函数允许我们在程序中并行执行多个任务。我们可以使用`async`关键字定义函数以使其成为异步函数。之后,我们可以在函数内部使用`await`关键字来等待Promise结果。有时,在没有从Promise获取结果的情况下,我们无法在函数中执行其他任务。因此,我们必须等待结果,这可以通过使用`await`关键字来实现。
语法
用户可以按照以下语法使用try-catch块来处理在将Promise与await关键字一起使用时出现的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()`函数,该函数返回一个被拒绝的Promise。在异步函数中,我们使用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时添加了计时器。
当用户单击“执行Promise”按钮时,它将执行`executePromise()`函数。在`executePromise()`函数中,我们使用await关键字调用`timerPromise()`,`timerPromise()`在5秒内拒绝Promise,并且在此之前函数等待继续执行。
<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秒钟才能被拒绝。
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP