跳到主要内容

async 函数

Generator 函数的语法糖,将 Generator 函数的星号(*)替换成 async,将 yield 替换成 await。ES2017 标准引入了 async 函数,使得异步操作变得更加方便。

特点

  • 内置执行器。
  • 更好的语义。
  • 更广的适用性。
  • 返回值是 Promise。

基本用法

遇到 await 就会先返回,等到异步操作完成,再接着执行函数体内后面的语句。

// 函数声明
async function foo() {}

// 函数表达式
const foo = async function () {};

// 对象的方法
let obj = { async foo() {} };

// Class 的方法
class Storage {
async foo(name) {}
}

// 箭头函数
const foo = async () => {};

错误处理机制。

async function f() {
await Promise.reject("出错了");
}

f()
.then((v) => console.log(v))
.catch((e) => console.log(e));

按顺序完成异步操作

async function logInOrder(urls) {
// 并发读取远程URL
const textPromises = urls.map(async (url) => {
const response = await fetch(url);
return response.text();
});

// 按次序输出
for (const textPromise of textPromises) {
console.log(await textPromise);
}
}

顶层 await

ES2022 开始,允许在模块的顶层独立使用 await 命令,设计目的使用 await 解决模块异步加载的问题。

提示

顶层 await 只能用在 ES6 模块,不能用在 CommonJS 模块。这是因为 CommonJS 模块的 require()是同步加载,如果有顶层 await,就没法处理加载了。

const strings = await import();