Async/Await异步

Async/Await是目前异步最好的结局方案。


 

let p1=function () {
        return new Promise((resolve)=>{
            setTimeout(()=>resolve(),4000);
        });
    };
let fun=async function () {
        console.log('1111');
        await p1();
        console.log('2222');
}
fun();

上面代码先输出了1等待了4秒然后输出了2。

使用async来标识这个函数为async函数。await只能出现在async函数中。await标识等待执行结束在执行下面的代码。

 

返回值


 

await不需要使用then可以直接得到返回值

let p1=function () {
        return new Promise((resolve)=>{
            setTimeout(()=>resolve('111'),1000);
        });
    };
    let fun=async function () {
        let message= await p1();
        console.log(message)
    }
    fun();

 

异常


await可以直接捕获异常

let p1=function () {
        return new Promise((resolve,reject)=>{
            setTimeout(()=>reject('error'),1000);
        });
    };
    let fun=async function () {
        try {
            let message= await p1();
            console.log(message)
        }
        catch(ex){
            console.log(ex);
        }

    }
    fun();

  

 

posted @ 2017-12-20 15:33  不骄不傲  阅读(289)  评论(0编辑  收藏  举报