Async和Await简介

  Async+Await相较于promise代码,优雅简洁了不少,避免了.then嵌套回掉...promise

Async关键字

async function fun1(){   return  "hello world"}function  fun2() {      console.log("我是后面的程序")}fun1().then(value=>{    console.log(value)})fun2();
//我是后面的程序
//hello world复制代码

console.log(fun1())复制代码

     async 语法相对比较简洁在函数前面添加async关键字,表示此函数为一个异步函数,便是异步,就表示不会阻塞后面的程序,因此hello world后输出,直接调用fun1()不会输出hello world,经过打印输出,咱们发现它返回的是一个promise对象,因此须要.then()回掉函数,输出promise返回值。bash


let promise = new Promise((resolve, reject) => {    setTimeout(() => {        let flag=false        if (flag) {            resolve('success')        } else {            reject('failed')        }       }, 1000)})async function test() {    let result =  promise    return result  }test().then(response => {    console.log(response) }).catch(error => {    console.log(error)})复制代码

   当async有返回值,调用该函数时,内部会调用promise.resolve()把它转化成一个对象返回,promis当内部抛出错误时,会调用promise.reject()返回错误的值,promise对象用catch方法进行错误捕获。
异步

Await等待什么呢?

   

function promise(num){    return new Promise((resolve,reject)=>{        setTimeout(function(){             resolve(2*num)         },3000)               })}async function fun4(){    let result =await promise(20);    console.log(result)    console.log("我是后面的程序")}fun4()//3秒后先输出40,再输出我是后面的程序复制代码

await 必须和async搭配使用,它等待的是一个promise对象执行完,并返回promise.resolve的值,当结果出现时再继续执行后面的代码,当等待结果发生异常如何处理呢?用try/catch,把await放到try里来执行,用catch来处理异常。async

function promise(num){    return new Promise((resolve,reject)=>{        setTimeout(function(){             resolve(2*num)         },3000)               })}function num1(n){    return promise(n)}function num2(n){    return promise(n)}function num3(n){    return promise(n)}

//promise方式async function fun4(){    const time1 = 10;    num1(time1)        .then(time2 => num2(time2))        .then(time3 => num3(time3))        .then(result => {            console.log(`result is ${result}`);        });    // let result =await promise(20);    // console.log(result)    console.log("我是后面的程序")//这个函数中,我是后面的程序先执行,.then异步执行

}
//我是后面的程序,result is 80//async+await方式
async function fun4(){    const time1 = 10;    const time2 = await num1(time1);    const time3 = await num2(time2);    const result = await num3(time3);    console.log(`result is ${result}`);    console.log("我是后面的程序")//这个函数中,我是后面的程序后执行,await先执行,获得结果后再执行后面的代码}fun4()//result is 80  我是后面的程序复制代码

    使用promise时都是用.then回掉处理返回的值,用await便避免了.then嵌套回掉,把异步用同步方式来实现了,没有回掉调用感受。
函数

总结

使用 async / await, 搭配 promise, 能够经过编写形似同步的代码来处理异步流程, 提升代码的简洁性和可读性。ui

Async Await 的优势:spa

一、解决了回调地狱的问题
二、能够添加返回值 return xxx;
三、能够在代码中添加try/catch捕获错误3d

相关文章
相关标签/搜索