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

docs: edit async

This commit is contained in:
ruanyf 2018-12-05 13:49:30 +08:00
parent 6914670a90
commit 6b74886920
2 changed files with 23 additions and 1 deletions

View File

@ -28,7 +28,7 @@ const gen = function* () {
};
```
写成`async`函数,就是下面这样。
上面代码的函数`gen`可以写成`async`函数,就是下面这样。
```javascript
const asyncReadFile = async function () {
@ -504,6 +504,27 @@ console.log(await res.text());
上面代码中,第二种写法的脚本必须使用`esm`加载器,才会生效。
第四点async 函数可以保留运行堆栈。
```javascript
const a = () => {
b().then(() => c());
};
```
上面代码中,函数`a`内部运行了一个异步任务`b()`。当`b()`运行的时候,函数`a()`不会中断,而是继续执行。等到`b()`运行结束,可能`a()`早就运行结束了,`b()`所在的上下文环境已经消失了。如果`b()``c()`报错,错误堆栈将不包括`a()`
现在将这个例子改成`async`函数。
```javascript
const a = async () => {
await b();
c();
};
```
上面代码中,`b()`运行的时候,`a()`是暂停执行,上下文环境都保存着。一旦`b()``c()`,错误堆栈将包括`a()`
## async 函数的实现原理
async 函数的实现原理,就是将 Generator 函数和自动执行器,包装在一个函数里。

View File

@ -192,6 +192,7 @@
- Axel Rauschmayer, [ES proposal: asynchronous iteration](http://www.2ality.com/2016/10/asynchronous-iteration.html): 异步遍历器的详细介绍
- Dima Grossman, [How to write async await without try-catch blocks in Javascript](http://blog.grossman.io/how-to-write-async-await-without-try-catch-blocks-in-javascript/): 除了 try/catch 以外的 async 函数内部捕捉错误的方法
- Mostafa Gaafa, [6 Reasons Why JavaScripts Async/Await Blows Promises Away](https://hackernoon.com/6-reasons-why-javascripts-async-await-blows-promises-away-tutorial-c7ec10518dd9): Async 函数的6个好处
- Mathias Bynens, [Asynchronous stack traces: why await beats Promise#then()](https://mathiasbynens.be/notes/async-stack-traces): async 函数可以保留错误堆栈
## Class