使用await在JavaScript中捕获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 ,因为它成功解决了。逻辑部分涉及到我们需要使用 catch 块来处理错误的第二个 promise。在输出中,用户可以观察到来自 catch 块的 testPromise2 的 promise 消息被打印出来。
<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块来处理使用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>
示例
在下面的示例中,我们创建了一个承诺,就像在上面的示例中创建的一样,但是我们在拒绝承诺时添加了定时器。
当用户点击“ 执行承诺 ”按钮时,它会执行 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秒钟来被拒绝。