Skip to content

ES6 之 async, await #35

@chenhuiYj

Description

@chenhuiYj

字面意思来理解。async 是“异步”的意思,await 可以认为是 async wait 的简写。就是用 async 来申明一个异步 function 的,而 await 用于等待一个异步方法执行完成。所以在写 await 的时候,里面的函数必须是异步的函数,就是 function 必须要用 async 声明。

async 和 await 用了同步的方式去做异步,async 定义的函数的返回值都是 promise,await 后面的函数会先执行一遍,然后就会跳出整个 async 函数来执行后面js栈的代码

本质上也是利用promise,下面两段代码是等同的。

async function test(){
	return ‘hello async’
}
//第二段代码
async function test(){
	return new Promise((resolve,reject)=>{
		resolve(‘hello async’)
	})
}

自然async也是前端微任务

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

async function testAsync1() {
    console.log("hello async");
}
let result1 = testAsync1();
console.log(result1);// Promise {<fulfilled>: undefined}

从结果中可以看到async函数返回的是一个promise对象,如果在函数中 return 一个直接量,async 会把这个直接量通过 Promise.resolve() 封装成 Promise 对象。如果asyn函数没有返回值,结果返回Promise.resolve(undefined)

1.相比于 Promise,它能更好地处理 then 链

下面实例:step1,step2,step3按顺序执行

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(time2))
        .then(time3 => step3(time3))
        .then(result => {
            console.log(`result is ${result}`);
        });
}
doIt();

链式调用then,使得代码难以阅读,维护。

如果用 async/await 来实现的话,会是这样:

async function doIt() {
    console.time("doIt");
    const time1 = 300;
    const time2 = await step1(time1);
    const time3 = await step2(time2);
    const result = await step3(time3);
    console.log(`result is ${result}`);
}
doIt();

仍然是三个步骤,但每一个步骤都需要之前每个步骤的结果。Pomise的实现看着很晕,传递参数太过麻烦。

function doIt() {
    console.time("doIt");
    const time1 = 300;
    step1(time1)
        .then(time2 => {
            return step2(time1, time2)
                .then(time3 => [time1, time2, time3]);
        })
        .then(times => {
            const [time1, time2, time3] = times;
            return step3(time1, time2, time3);
        })
        .then(result => {
            console.log(`result is ${result}`);
        });
}
doIt();

用 async/await 来写

async function doIt() {
    console.time("doIt");
    const time1 = 300;
    const time2 = await step1(time1);
    const time3 = await step2(time1, time2);
    const result = await step3(time1, time2, time3);
    console.log(`result is ${result}`);
}
doIt();

2.捕捉错误

await 命令后面的 Promise 对象,运行结果可能是 rejected,把 await 命令放在 try...catch 代码块中可以捕捉到错误

async function myFunction() {
  try {
    await somethingThatReturnsAPromise();
  } catch (err) {
    console.log(err);
  }
}

// 另一种写法

async function myFunction() {
  await somethingThatReturnsAPromise().catch(function (err){
    console.log(err);
  });
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions