2
写在前面

本文内容及代码均摘取出自一歩的相关教程。
本文仅作为个人笔记练习代码使用(所有的代码都需要自己手动敲上几遍),内容上也精简了很多。
相关知识还请阅读原文:异步神器 async-await

async-await
  • async-await是promise和generator的语法糖;
  • async返回的是一个promise对象,即可以使用then添加回调;
  • await只能在async的上下文中使用,不然会报错;
  • await可以等待两种返回值,promise或其他:

    • promise:造成异步函数停止执行,并等待promise的resolve;
    • 其他:立即执行
  • async-await的错误处理(try-catch);
  • async-await的并行处理(Promise.all);

上述总结具体代码演示如下:

// async返回promise;
async function demo1() {
    var num = Math.random();
    return num; // 相当于Promise.resolve(num);
}
demo().then(value => {
    alert(value);
})
// await只能在async上下文中使用
function notAsyncFunc() {
    return await Math.random();
}
notAsyncFunc();
// Uncaught SyntaxError: await is only valid in async function 

async function demo2() {
    for(i=0;i<5;i++) {
        await console.log(Math.random());
    }
}
demo2(); // 可以正常执行,打印5个随机数

async function errorDemo2() {
    for(i=0;i<5;i++) {
        setTimeout(()=>{await console.log('test2')}))
    }
}
errorDemo2();
// Uncaught SyntaxError: await is only valid in async function
// await的两种等待对象;
function promiseObj() {
    return new Promise((resolve,reject) => {
        setTimeout(resolve,1000,'promise!')
    })
}
function otherObj() {
    setTimeout(()=>console.log('otherObj!'),2000)
    // 或者是一个表达式等任何非promise对象
}

async function awaitDemo() {
    await otherObj();
    console.log('other!');
    let result = await promiseObj();
    console.log(result);
    console.log('promiseObj!')
}
awaitDemo();
// other! 立即执行
// promise! 1s后执行
// promiseObj! 紧跟着上条执行
// otherObj! 2s后执行
// 异步等待的错误处理;
function sleep(second) {
    return new Promise((resolve,reject) => {
        setTimeout(() => {
            reject('want to sleep~');
        },second)
    })
}

async function errorDemo() {
    let result = await sleep(2000);
    console.log(result);
    // Uncaught (in promise) want to sleep~
}

async function correctDemo() {
    try {
        let result = await sleep(2000);
        console.log(result);
    } catch(err) {
        console.log(err);
        // want to sleep~
    }
}
// 异步等待的并行处理;
function sleep(second) {
    return new Promise((resolve,reject) => {
        setTimeout(() => {
            resolve('done!' + Math.random());
        },second);
    })
}

async function bugDemo() {
    await sleep(1000);
    await sleep(2000);
    await sleep(3000);
    console.log('clear the loading~');
}

async function correctDemo() {
    let p1 = sleep(1000);
    let p2 = sleep(2000);
    let p3 = sleep(3000);
    await Promise.all([p1,p2,p3]);
    console.log('clear the loading~');
}

bugDemo(); // 6s后输出 clear the loading~
correctDemo(); // 3s后输出 clear the loading~
promise 和 async-await的关系
  • async-await只是promise的语法糖;
  • async-await简化了promise的实现;
// 需求:以请求1的结果作为参数,发出请求2
function request(second,param) {
    return new Promise((resolve,reject) => {
        setTimeout(resolve,second,param)
    })
}
// promise实现
function promiseFunc() {
    let result1,result2,result3;
    request(2000,'req01').then(res => {
        result1 = res;
        return request(1000,'req02' + res)
    })
    .then(res => {
        result2 = res;
        return request(500,'req03' + res);
    })
    .then(res => {
        result3 = res;
    })
    .finally(() => {
        console.log(`
            ${result1}
            ${result2}
            ${result3}
        `)
    })
}
// async-await实现
async function asyncFunc() {
    let result1 = await request(2000,'req01');
    let result2 = await request(1000,'req02' + result1);
    let result3 = await request(500,'req03' + result2);
    console.log(`
        ${result1}
        ${result2}
        ${result3}
    `);
}
  • async-await的本质上还是promise;
// 见上面Promise.all那个例子

時雨
91 声望6 粉丝

慢慢地把云笔记上的内容搬过来~