【转】6 Reasons Why JavaScript’s Async/Await Blows Promises Away (Tutorial)
----------------------------------------------------------------------------------------------
6 Reasons Why JavaScript’s Async/Await Blows Promises Away (Tutorial)
In case you missed it, Node now supports async/await out of the box since version 7.6. If you haven’t tried it yet, here are a bunch of reasons with examples why you should adopt it immediately and never look back.
[UPDATE]: Node 8 LTS is out now with full Async/Await support.
[EDIT]: It seems that the embedded code on gist does not work on medium native app, but it works on mobile browsers. If you are reading this on the app, tap on the share icon and choose “open in browser” in order to see code snippets.
Async/await 101
For those who have never heard of this topic before, here’s a quick intro
- Async/await is a new way to write asynchronous code. Previous options for asynchronous code are callbacks and promises.
- Async/await is actually built on top of promises. It cannot be used with plain callbacks or node callbacks.
- Async/await is, like promises, non blocking.
- Async/await makes asynchronous code look and behave a little more like synchronous code. This is where all its power lies.
Syntax
Assuming a function getJSON
that returns a promise, and that promise resolves with some JSON object. We just want to call it and log that JSON, then return "done"
.
This is how you would implement it using promises
const makeRequest = () =>
getJSON()
.then(data => {
console.log(data)
return "done"
}) makeRequest()
And this is how it looks with async/await
const makeRequest = async () => {
console.log(await getJSON())
return "done"
} makeRequest()
There are a few differences here
- Our function has the keyword
async
before it. Theawait
keyword can only be used inside functions defined withasync
. Anyasync
function returns a promise implicitly, and the resolve value of the promise will be whatever youreturn
from the function (which is the string"done"
in our case). - The above point implies that we can’t use await in the top level of our code since that is not inside an
async
function.
3. await getJSON()
means that the console.log
call will wait until getJSON()
promise resolves and print it value.
Why Is It better?
1. Concise and clean
Look at how much code we didn’t write! Even in the contrived example above, it’s clear we saved a decent amount of code. We didn’t have to write .then
, create an anonymous function to handle the response, or give a name data
to a variable that we don’t need to use. We also avoided nesting our code. These small advantages add up quickly, which will become more obvious in the following code examples.
2. Error handling
Async/await makes it finally possible to handle both synchronous and asynchronous errors with the same construct, good old try/catch
. In the example below with promises, the try/catch
will not handle if JSON.parse
fails because it’s happening inside a promise. We need to call .catch
on the promise and duplicate our error handling code, which will (hopefully) be more sophisticated than console.log
in your production ready code.
Now look at the same code with async/await. The catch
block now will handle parsing errors.
3. Conditionals
Imagine something like the code below which fetches some data and decides whether it should return that or get more details based on some value in the data.
Just looking at this gives you a headache. It’s easy to get lost in all that nesting (6 levels), braces, and return statements that are only needed to propagate the final result up to the main promise.
This example becomes way more readable when rewritten with async/await.
4. Intermediate values
You have probably found yourself in a situation where you call a promise1
and then use what it returns to call promise2
, then use the results of both promises to call a promise3
. Your code most likely looked like this
If promise3
didn’t require value1
it would be easy to flatten the promise nesting a bit. If you are the kind of person who couldn’t live with this, you could wrap both values 1 & 2 in a Promise.all
and avoid deeper nesting, like this
This approach sacrifices semantics for the sake of readability. There is no reason for value1
& value2
to belong in an array together, except to avoid nesting promises.
This same logic becomes ridiculously simple and intuitive with async/await. It makes you wonder about all the things you could have done in the time that you spent struggling to make promises look less hideous.
5. Error stacks
Imagine a piece of code that calls multiple promises in a chain, and somewhere down the chain an error is thrown.
The error stack returned from a promise chain gives no clue of where the error happened. Even worse, it’s misleading; the only function name it contains is callAPromise
which is totally innocent of this error (the file and line number are still useful though).
However, the error stack from async/await points to the function that contains the error
This is not a huge plus when you’re developing on your local environment and have the file open in an editor, but it’s quite useful when you’re trying to make sense of error logs coming from your production server. In such cases, knowing the error happened in makeRequest
is better than knowing that the error came from a then
after a then
after a then
…
6. Debugging
Last but not least, a killer advantage when using async/await is that it’s much easier to debug. Debugging promises has always been such a pain for 2 reasons
- You can’t set breakpoints in arrow functions that return expressions (no body).

Try setting a breakpoint anywhere here
2. If you set a breakpoint inside a .then
block and use debug shortcuts like step-over, the debugger will not move to the the following .then
because it only “steps” through synchronous code.
With async/await you don’t need arrow functions as much, and you can step through await calls exactly as if they were normal synchronous calls.

In Conclusion
Async/await is one of the most revolutionary features that have been added to JavaScript in the past few years. It makes you realize what a syntactical mess promises are, and provides an intuitive replacement.
Concerns
Some valid skepticism you might have about using this feature
- It makes asynchronous code less obvious: Our eyes learned to spot asynchronous code whenever we see a callback or a
.then
, it will take a few weeks for your eyes to adjust to the new signs, but C# had this feature for years and people who are familiar with it know it’s worth this minor, temporary inconvenience. - Node 7 is not an LTS release: Yes, but node 8 is coming next month, and migrating you codebase to the new version will most likely take little to no effort. [UPDATE]: Node 8 LTS is now out.
【转】6 Reasons Why JavaScript’s Async/Await Blows Promises Away (Tutorial)的更多相关文章
- [转] 理解 JavaScript 的 async/await
[From] https://segmentfault.com/a/1190000007535316 边城 2016年11月19日发布 随着 Node 7 的发布,越来越多的人开始研究据说是 ...
- 【前端_js】理解 JavaScript 的 async/await
async 和 await 在干什么 任意一个名称都是有意义的,先从字面意思来理解.async 是“异步”的简写,而 await 可以认为是 async wait 的简写.所以应该很好理解 async ...
- 理解 JavaScript 的 async/await
随着 Node 7 的发布,越来越多的人开始研究据说是异步编程终级解决方案的 async/await.我第一次看到这组关键字并不是在 JavaScript 语言里,而是在 c# 5.0 的语法中.C# ...
- [转] Understanding JavaScript’s async await
PS:Promise的用处是异步调用,这个对象使用的时候,call then函数,传一个处理函数进去,处理异步调用后的结果 Promise<Action>这样的对象呢,异步调用后的结果是一 ...
- JavaScript 的 Async\/Await 完胜 Promise 的六
参考:http://www.10tiao.com/html/558/201705/2650964601/1.html Node 现在从版本 7.6 开始就支持 async/await 了. 简介: A ...
- 深入理解理解 JavaScript 的 async/await
原文地址:https://segmentfault.com/a/1190000007535316,首先感谢原文作者对该知识的总结与分享.本文是在自己理解的基础上略作修改所写,主要为了加深对该知识点的理 ...
- JavaScript 的 async/await
随着 Node 7 的发布,越来越多的人开始研究据说是异步编程终级解决方案的 async/await. 异步编程的最高境界,就是根本不用关心它是不是异步. async 函数就是隧道尽头的亮光,很多人认 ...
- JavaScript 利用 async await 实现 sleep 效果
const sleep = (timeountMS) => new Promise((resolve) => { setTimeout(resolve, timeountMS); }); ...
- Async/Await替代Promise的6个理由
译者按: Node.js的异步编程方式有效提高了应用性能:然而回调地狱却让人望而生畏,Promise让我们告别回调函数,写出更优雅的异步代码:在实践过程中,却发现Promise并不完美:技术进步是无止 ...
随机推荐
- Sharepoint 2010 TimerJob重复
昨天被TimerJob困扰了一天.原因就是TimerJob当中会有一个Httpwebrequest GET请求一个Application Page进行一些操作(其中有一个操作是发送邮件).但是发现随机 ...
- Mac 命令行美化
在 mac 中使用原生的命令行工具,竟然没有 git 命令的自动补全,在 git 仓库下也看不到当前的分支名,不能忍.于是,开始一波改造. 目标:命名 Tab 自动补全:可以显示分支名: 一番 Goo ...
- CentOS 7中以runfile形式安装CUDA 9.0
GPU: NVIDIA Tesla K40C Enter the 'root' mode: $ su - 1. Pre-installation 1.1 Verify you have a CUDA- ...
- nyoj 作业题 dp
作业题 时间限制:3000 ms | 内存限制:65535 KB 难度:3 描述 小白同学这学期有一门课程叫做<数值计算方法>,这是一门有效使用数字计算机求数学问题近似解的方法与过程, ...
- C和指针之学习笔记(4)
第9章 字符串 字符串的输入与输出 int ch; char strings[80]; FILE *input; (1)scanf(“%c”,&ch); printf(“%c \n” ...
- Hibernate iterate(迭代)
在Hibernate中,有它自己的iterate方法.这里是一个n+1的问题,n代表数据量,而1表示查询所有的主键. 这里与List进行比较. 这里使用list时会将所有数据查询出来. 而在使用ite ...
- lightoj 1306 - Solutions to an Equation 扩展的欧几里得
思路:看题就知道用扩展的欧几里得算法做!!! 首先我们可以求出ax+by=gcd(a,b)=g的一个组解(x0,y0).而要使ax+by=c有解,必须有c%g==0. 继而可以得到ax+by=c的一个 ...
- 第2篇--JVM的内存区域划分
学过C语言的朋友都知道C编译器在划分内存区域的时候经常将管理的区域划分为数据段和代码段,数据段包括堆.栈以及静态数据区.那么在Java语言当中,内存又是如何划分的呢? 由于Java程序是交由JVM执行 ...
- bzoj 2434 ac自动机
ac自动机中,如果以trie中的节点为节点,(fail[i],i)为边,可以建立一颗树,该树有如下特点:“节点u是节点v的祖先 当且仅当 u代表的字符串是v代表的字符串的一个后缀”.(u代表的字符串是 ...
- noip2011初赛提高组 试题详解
转载自:https://blog.csdn.net/Eirlys_North/article/details/52889993 一.单项选择题(共20题,每题1.5分,共计30分,每题有且仅有一个正确 ...