1
0
mirror of https://github.com/ruanyf/es6tutorial.git synced 2025-05-24 18:32:22 +00:00

docs(async): edit await

This commit is contained in:
ruanyf 2017-08-18 13:16:46 +08:00
parent 5a448720c7
commit 7f0180caca

View File

@ -460,6 +460,24 @@ async function dbFuc(db) {
}
```
目前,[`@std/esm`](https://www.npmjs.com/package/@std/esm)模块加载器支持顶层`await`,即`await`命令可以不放在 async 函数里面,直接使用。
```javascript
// async 函数的写法
const start = async () => {
const res = await fetch('google.com');
return res.text();
};
start().then(console.log);
// 顶层 await 的写法
const res = await fetch('google.com');
console.log(await res.text());
```
上面代码中,第二种写法的脚本必须使用`@std/esm`加载器,才会生效。
## async 函数的实现原理
async 函数的实现原理,就是将 Generator 函数和自动执行器,包装在一个函数里。