From 6b74886920c86426728b344ef564169cf99024f7 Mon Sep 17 00:00:00 2001 From: ruanyf Date: Wed, 5 Dec 2018 13:49:30 +0800 Subject: [PATCH] docs: edit async --- docs/async.md | 23 ++++++++++++++++++++++- docs/reference.md | 1 + 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/docs/async.md b/docs/async.md index 82fca81..16afbba 100644 --- a/docs/async.md +++ b/docs/async.md @@ -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 函数和自动执行器,包装在一个函数里。 diff --git a/docs/reference.md b/docs/reference.md index 1db39b4..be0eedd 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -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 JavaScript’s 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