ES2017 async 函数

async 和 await 在干什么

  • 每个名称都有意义
    • async : 异步
    • await: async wait简写 异步等待
  • 所以很好理解 async 是声明一个函数是异步的,而await是用于等待一个异步方法执完成。

async 起什么作用

async function testAsync() {
    return "hello async";
}
let result = testAsync()
console.log(result) //Promise { 'hello async' }

以上代码输出的是了一个Promise 对象

  • 如果在 async 函数中 return 一个直接量, async 会把这个直接量通过 Promise.resolve() 封装成 Promise 对象。
  • 所以正确的输出方式应该是
async function testAsync() {
    return "hello async";
}
testAsync().then(res => console.log(res)) //'hello async'
  • 如果async 函数没有返回值 它就会返回 Promise.resolve(undefined)

await 到底在等啥

  • 按意思说 await 就是异步等待 等待着一个返回值,而实际上await 等待就是一个Promise对象 或者 是其它值。

  • 因为 async 返回的是一个Promise 对象,所以 await 等待就是 async 的返回值。

  • 但要清楚,它等的实际是一个返回值。注意到 await 不仅仅用于等 Promise 对象,它可以等任意表达式的结果,所以,await 后面实际是可以接普通函数调用或者直接量的。

function getSomething() {
    return "something";
}

async function testAsync() {
    return Promise.resolve("hello async");
}

async function test() {
    const v1 = await getSomething();
    const v2 = await testAsync();
    console.log(v1, v2);
}

test() // something hello async

所以以上代码是可以正确运行的

相比之下 async 和 await 到底有什么优势

  • 看代码
function takeLongTime(n) {
    return new Promise(resolve => {
        setTimeout(() => resolve(n + 200), n);
    });
}

function step1(n) {
    console.log(`step1 with ${n}`);
    return takeLongTime(n);
}

function step2(n) {
    console.log(`step2 with ${n}`);
    return takeLongTime(n);
}

function step3(n) {
    console.log(`step3 with ${n}`);
    return takeLongTime(n);
}
  • 用Promise 输出
function doIt() {
    console.time("doIt");
    const time1 = 300;
    step1(time1)
        .then(time2 => step2(time1))
        .then(time3 => step3(time1))
        .then(result => {
            console.log(`result is ${result}`);
            console.timeEnd("doIt");
        });
}

doIt();
// step1 with 300
// step2 with 500
// step3 with 700
// result is 900
// doIt: 1507.251ms
  • 用async await
async function doIt() {
    console.time("doIt");
    const time1 = 300;
    const time2 = await step1(time1);
    const time3 = await step2(time1);
    const result = await step3(time1);
    console.log(`result is ${result}`);
    console.timeEnd("doIt");
}
doIt();
// step1 with 300
// step2 with 500
// step3 with 700
// result is 900
// doIt: 1507.251ms

你可能感兴趣的:(ES2017 async 函数)