一眼看懂promise async的区别

// promise方法
    let p1 = new Promise((resolve,reject) => {
        setTimeout(() => {
            resolve('我是p1')
        },4000)
    })
    let p2 = new Promise((resolve,reject) => {
        setTimeout(() => {
            resolve('我是p2')
        },200)
    })
    let p3 = new Promise((resolve,reject) => {
        setTimeout(() => {
            resolve('我是p3')
        },200)
    })
    // 想让p1完成后再执行P2再执行P3
    // 数量太多只能循环嵌套
    p1.then((res) => {
        console.log(res);
        p2.then((res) => {
            console.log(res);
            p3.then((res) => {
                console.log(res);
            })
        })
    })
    
    



    // async  await语法糖
    let a1=()=>{
        return new Promise((resolve,reject) => {
            setTimeout(() => {
                resolve('我是a1')
            },4000)
        })
    } 
    let a2=()=>{
        return new Promise((resolve,reject) => {
            setTimeout(() => {
                resolve('我是a2')
            },40)
        })
    } 
    let a3=()=>{
        return new Promise((resolve,reject) => {
            setTimeout(() => {
                resolve('我是a3')
            },40)
        })
    } 
    // 想让a1完成后再执行a2再执行a3
    //能避免回调
    async function asy(){
        await a1().then((res) => {console.log(res)});
        await a2().then((res) => {console.log(res)});
        await a3().then((res) => {console.log(res)});
    }
    asy();
posted @ 2019-05-08 14:30  liyichao  阅读(1857)  评论(0编辑  收藏  举报