理解 async/await 的使用

830 阅读1分钟

栗子

// Promise 写法

let p1 = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve(111);
    }, 1000)
})
let p2 = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve(2222);
    }, 2000)
})

p1.then(res=>{
    console.log(res);
    return p2;
}).then(res=>{
    console.log(res)
}).catch(err=>{
    console.log(err);
})

// 改写成async 和 await(目前)

async function asyncFn() {
    // 异步过程  同步写法;
    // await 后面跟的一定是 promise 对象;
    try {
        let res1 = await p1;
        console.log(res1);
        let res2 = await p2;
        console.log(res2)
    } catch (err) {
        console.log("??",err);
    }
}
asyncFn();

不会相互等待的写法

function test(){
    p1.then(res=>{

    })
    p2.then(res=>{

    })
}
  1. async
// async 告诉浏览器,这个方法里包含了关于异步处理的信息
async function fn(){
    // 等待执行完毕再走下一步
    // 读到await 这里是异步处理
    // await 跟着Promise一起使用, 或者写一个方法,方法里有一个Promise,否则无法得知此时异步处理的状态
    let a = await new Promise((resolve)=>{
        setTimeout(()=>{
            console.log(1);
            resolve(10);  // resolve的参数能返回执行结果给a = 10
        },1000);
    });
    let b = await new Promise((resolve)=>{
        setTimeout(()=>{
            console.log(2);
            resolve(20);  // b = 20
        },1000);
    });
    console.log(a+b); // 30
}    
fn();
  1. 错误捕获
window.onload = function(){
    let box = document.querySelector("#box");
    async function fn(){
    <!--卸载try里的会被捕获-->
        try{
            box.style.width = "200px";
            await new Promise((resolve)=>{
                setTimeout(()=>{
                    box.style.height = "200px";
                    resolve();
                },1000)
            });
            await new Promise((resolve,reject)=>{
                setTimeout(()=>{
                    box.style.transform = "rotate(360deg) scale(.1)";
                    reject("出错了"); // 出错了直接跳到catch 下面的不执行,看下图运行结果
                },1000)
            });
            await new Promise((resolve)=>{
                setTimeout(()=>{
                    box.style.transform = "rotate(0deg) scale(1)";
                    resolve();
                },1000);
            })
            setTimeout(()=>{
                console.log("动画完成");
            },1000);
        } catch(err) {
        <!--出错之后要做的事情-->
            console.log(err);
        }
    }
    fn()
    console.log("嘿嘿嘿");
};