zoukankan      html  css  js  c++  java
  • 什么是async和await? 怎么捕获异常?

    1.async和await?

    async/await主要用于进行异步请求。

    1.1被async修饰的函数是异步函数,异步函数就是代码执行起来不会阻塞后面后面代码的进程。

    1.3async返回一个Promise对象,await等待一个Promise对象,而await等待的就是async返回的Promise对象返回的结果。

    async返回一个promise对象

    async function test(){
               return "hello word"
            
           }
           console.log(test()) //Promise {<fulfilled>: "hello word"}
            test().then((res)=>{
                console.log(res)//hello word
            }).catch((err)=>{
                console.log(new Error())
            })
           

    要是想得async函数的结果,用.then().catch()方法来注册回调函数

    注意:若异步函数内部返回的是一个直接量,则async会把这个直接量用Promise.resolve转成Promise对象

    总结:async函数执行返回一个Promise对象,并把函数内部的值用Promise.resolve进行了封装

    2.await等待

    2.1 await放在异步函数内部,await后面跟一个表达式,一般都是Promise对象的表达式

    2.2 在async函数执行过程中,遇到await关键字时会先暂停,等触发的异步操作完成后,在执行async函数。

      function test1(){
               console.log("test1")
            };
           async function test(){
               const res=await test1() 
                console.log("test")
           }
          test();//test1  test

    3.2await等到是后边表达式的结果  返回的结果有两种①Promise对象②不是promise对象

    ①Promise对象

    如果等待的对象是promise,会暂停await后面的执行,先执行async外部的同步代码,然后再执行内部的代码,并将得到的结果直接作为await的结果。

    ②非Promise对象

    如果等待的是Promise对象,同样会暂停await后面的执行限制性async外部的同步代码,等着 Promise 对象 fulfilled,然后把 resolve 的参数作为 await 表达式的运算结果。

    3.异常捕获

    try/catch捕获异常

      async function test(){
               const res=await test1().catch((err)=>{
                    console.log(new Error)
                   }) 
                console.log("test")
           }

      async function test(){
               try{
               const res=await test1()
               }catch(err){
                console.log(err)
               }
                console.log("test")
           }
  • 相关阅读:
    C/C++操作MySQL数据库——增、删、改、查
    Mysql常用命令行大全——转载
    .NET Framework、C#、ASP.NET之间的关系
    委托和事件
    ASP.NET 页生命周期概述
    在SqlServer下增加MySql的链接服务器
    Head First 设计模式----DecoratorPattern
    jquery easyui----tree
    Head First 设计模式----ObserverPattern
    Jquery easyui----combotree
  • 原文地址:https://www.cnblogs.com/babilong/p/13432614.html
Copyright © 2011-2022 走看看