【笔记】JS的异步

前言

JS的异步学习笔记

异步函数

定义异步函数

  • 通过async关键字定义异步函数
1
async function fn() {}

通过变量接收异步函数

1
const fn = async function () {};

通过箭头函数定义异步函数

1
const fn = async () => {};

执行异步函数

  • 异步函数中定义的代码和普通函数一样会直接执行,而不是返回生成器对象
1
2
3
async function fn() {}

fn();

异步函数的返回值

  • 异步函数的返回值是一个Promise对象
1
2
3
4
5
6
7
async function fn() {
return "value";
}

fn().then((res) => {
console.log(res); // "value"
});
1
2
3
4
5
6
7
function fn() {
return Promie.resolve("value");
}

fn().then((res) => {
console.log(res); // "value"
});

异步函数可以返回的值

返回普通值
1
2
3
4
5
async function fn() {
return "value";
}

fn().then((res) => {}).catch((err) => {});
返回非thenable对象
1
2
3
4
5
async function fn() {
return {};
}

fn().then((res) => {}).catch((err) => {});
返回新Promise对象
1
2
3
4
5
6
7
async function fn() {
return new Promie((resolve, reject) => {
...
});
}

fn().then((res) => {}).catch((err) => {});
返回thenable对象
1
2
3
4
5
6
7
8
9
async function fn() {
return {
then: function (resolve, reject) {
...
}
};
}

fn().then((res) => {}).catch((err) => {});

await关键字

  • 异步函数中使用await关键字调用的函数,在执行时会等待函数调用产生结果才会继续向下执行

  • await关键字可以修饰普通函数

1
2
3
4
5
6
7
function getData(url) {}

async function fn() {
const result = await getData("");
}

fn();
  • await关键字也可以修饰异步函数
1
2
3
4
5
6
7
async function requestData(url) {}

async function fn() {
const result = await requestData("");
}

fn();
  • await关键字还可以修饰Promise对象
1
2
3
4
5
async function fn() {
const result = await new Promise((resolve, reject) => {});
}

fn();

类中定义异步方法

  • 在类中通过async定义的方法为异步方法
1
2
3
class Cls {
async method() {}
}

异步操作的实现方案

通过Promise实现异步

回调地狱(Callback Hell)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function requestData(url) {
return new Promise((resolve, reject) => {});
}

function getData() {
requestData("").then(res1 => {
requestData(res1).then(res2 => {
requestData(res2).then(res3 => {
console.log(res3);
});
});
});
}

getData();

链式调用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function requestData(url) {
return new Promise((resolve, reject) => {});
}

function getData() {
requestData("").then(res1 => {
return requestData(res1);
}).then(res2 => {
return requestData(res2);
}).then(res3 => {
console.log(res3);
});
}

getData();

通过生成器函数实现异步

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
function requestData(url) {
return new Promise((resolve, reject) => {});
}

function* getData() {
const res1 = yield requestData("");
const res2 = yield requestData(res1);
const res3 = yield requestData(res2);
console.log(res3);
}

const generator = getData();
generator.next().value.then((res1) => {
generator.next().value.then((res2) => {
generator.next().value.then((res3) => {
console.log(res3);
});
});
});

通过异步函数实现异步

  • 异步函数的实质是生成器的语法糖
1
2
3
4
5
6
7
8
9
10
11
12
function requestData(url) {
return new Promise((resolve, reject) => {});
}

async function getData() {
const res1 = await requestData("");
const res2 = await requestData(res1);
const res3 = await requestData(res2);
console.log(res3);
}

getData();

完成