Async和Await简介

744 阅读2分钟

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

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返回值。


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来处理异常。

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, 可以通过编写形似同步的代码来处理异步流程, 提高代码的简洁性和可读性。

Async Await 的优点:

1、解决了回调地狱的问题
2、可以添加返回值 return xxx;
3、可以在代码中添加try/catch捕获错误