chenhuiYj / chenhuiYj/note

ES6 之 async, await

Open
#35 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
HTML
Stars
6
Forks
0
PR merge metrics
No merged PRs in 30d

Description

字面意思来理解。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);
  });
}

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

The issue body contains a Chinese documentation draft about ES6 async/await, but it does not name a target file, documentation entry point, or test. First confirm where notes are stored and whether this content is intended to be added or revised; done means the approved article is placed in the project’s documentation structure and its examples are accurate.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript
Domain
documentation
Issue type
Documentation
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.