在 JavaScript 中使用 await 时使用 catch 处理 Promise 拒绝

javascriptweb developmentfront end technology

在 JavaScript 中,用户可以使用 Promise 执行特定操作。例如,我们可以创建承诺以使用 API 从数据库获取数据。如果承诺成功从数据库获取数据,则表示承诺成功,否则承诺出现错误,这意味着承诺被拒绝。

让我们先看看创建承诺的语法。

语法

用户可以按照以下语法在 JavaScript 中创建承诺。

let testPromise = new Promise((res, rej) => {
   
   // perform some operation
});

在上述语法中,我们使用了带有"new"关键字的 Promise() 构造函数来创建承诺。

示例

在下面的示例中,我们创建了两个不同的承诺。此外,我们还解析并拒绝了它们。

用户可以在下面的代码中看到我们如何管理 testPromise1,因为它已成功解析。逻辑部分来自第二个承诺,我们需要使用 catch 块来处理错误。在输出中,用户可以观察到 testPromise2 的承诺消息是从 catch 块中打印出来的。

<html>
<body>
   <h2><i>Promise</i> in JavaScript</h2>
   <p id = "output"> </p>
   <script>
      	let output = document.getElementById("output");
      
        // 创建 Promise 并解析它
        let testPromise1 = new Promise((res, rej) => {
        res("testPromise1 解析成功!");
        });
        
        // 拒绝 Promise
        let testPromise2 = new Promise((res, rej) => {
        rej("testPromise2 由于错误被拒绝!");
        });
        
        // 执行 testPromise1
        testPromise1.then((res) => {
        output.innerHTML += res;
        output.innerHTML += "</br>";
        });
        
        //执行 testPromise2,并使用 catch 块处理错误。
        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 关键字一起使用。因此,我们必须使用 try-catch 块来处理来自被拒绝的承诺的错误。

异步函数允许我们在程序中并行执行多个任务。我们可以定义函数,后跟 async 关键字以使其异步。之后,我们可以在函数中使用 await 关键字来等待承诺结果。有时,如果没有从承诺中获得结果,我们就无法在函数中执行其他任务。因此,我们必须等待使用 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 关键字等待承诺被实现或拒绝。

示例

在下面的示例中,我们创建了异步函数。此外,我们还创建了 promise1() 函数,该函数返回一个拒绝的承诺。在异步函数中,我们使用 await 关键字调用了 promise1() 函数,当承诺被拒绝时,控制权转到 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> 

在上面的输出中,用户可以观察到,当他们点击"执行承诺"按钮时,5 秒后,他们会看到来自 catch 块的错误消息,因为承诺需要 5 秒钟才能被拒绝。


相关文章