原文:https://hackernoon.com/6-reasons-why-javascripts-async-await-blows-promises-away-tutorial-c7ec10518dd9

----------------------------------------------------------------------------------------------

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

  1. Our function has the keyword async before it. The await keyword can only be used inside functions defined with asyncAny async function returns a promise implicitly, and the resolve value of the promise will be whatever you return from the function (which is the string "done" in our case).
  2. 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.parsefails 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 promise1and 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

  1. 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.

转载于:https://www.cnblogs.com/oxspirt/p/9768060.html

【转】6 Reasons Why JavaScript’s Async/Await Blows Promises Away (Tutorial)相关推荐

  1. Async/await 和 Promises 区别

    原文地址=> 6 Reasons Why JavaScript's Async/Await Blows Promises Away (Tutorial) Async/await 是建立在 Pro ...

  2. 理解 JavaScript 的 async/await

    随着 Node 7 的发布,越来越多的人开始研究据说是异步编程终级解决方案的 async/await.我第一次看到这组关键字并不是在 JavaScript 语言里,而是在 c# 5.0 的语法中.C# ...

  3. JavaScript 的 async/await 理解(4)

    随着 Node 7 的发布,越来越多的人开始研究据说是异步编程终级解决方案的 async/await.我第一次看到这组关键字并不是在 JavaScript 语言里,而是在 c# 5.0 的语法中.C# ...

  4. java有async和await吗,理解 JavaScript 的 async/await

    2020-06-04 更新 JavaScript 中的 async/await 是 AsyncFunction 特性 中的关键字.目前为止,除了 IE 之外,常用浏览器和 Node (v7.6+) 都 ...

  5. javascript中async await的用法

    2019独角兽企业重金招聘Python工程师标准>>> async和await必须成对出现,示例: function file2txtArr(file) {var fr = new ...

  6. Async/Await替代Promise的6个理由

    2019独角兽企业重金招聘Python工程师标准>>> 译者按: Node.js的异步编程方式有效提高了应用性能:然而回调地狱却让人望而生畏,Promise让我们告别回调函数,写出更 ...

  7. 8张图让你一步步看清 async/await 和 promise 的执行顺序

    2019独角兽企业重金招聘Python工程师标准>>> **摘要:**面试必问 原文:8张图帮你一步步看清 async/await 和 promise 的执行顺序 作者:ziwei3 ...

  8. async await

    随着 Node 7 的发布,越来越多的人开始研究据说是异步编程终级解决方案的 async/await.我第一次看到这组关键字并不是在 JavaScript 语言里,而是在 c# 5.0 的语法中.C# ...

  9. JavaScript是如何工作的:事件循环和异步编程的崛起+ 5种使用 async/await 更好地编码方式!...

    此篇是 JavaScript是如何工作的第四篇,其它三篇可以看这里: JavaScript是如何工作的:引擎,运行时和调用堆栈的概述! JavaScript是如何工作的:深入V8引擎&编写优化 ...

最新文章

  1. pyinstaller 打包tensorflow2.0为单个文件
  2. 基于Linux GlassFish v3 配置取代tomcat
  3. struts2 ajax请求发现执行action两次原因
  4. 机器学习知识点(七)决策树学习算法Java实现
  5. 快做这 15点,让 SpringBoot 启动更快一点!
  6. saas系统是什么_为什么SAAS食堂管理系统更受人们的欢迎?
  7. PTA 程序设计天梯赛(61~80题)
  8. 处女作:《游戏AI程序设计实战》2019.4.1
  9. nginx:工作原理
  10. 手机文字转语音简单方法分享
  11. 安卓微信分享图标不显示的问题
  12. PHP 代码 微信、公众号、企业微信 发送表情符号 [U+1F449]
  13. 重磅丨FIL10月减产即将到来 2分钟了解FIL分配模型
  14. 2021年数学建模国赛C题思路
  15. idea运行springboot出现Process finished with exit code -1073741819 (0xC0000005)
  16. 超级牛逼的立体画,太厉害了!
  17. STM32 BOOT模式配置以及作用
  18. Android编译Skia库
  19. 无序列表举例html,HTML中的无序列表讲解(菜鸟)
  20. K-近邻算法之K值的选择(带案例)

热门文章

  1. 【图解篇】斯达康XV6700刷机超完整教程!!!
  2. Css中Position属性的含义
  3. 图文并茂,万字详解,带你掌握 JVM 垃圾回收!
  4. 离职10天,面挂4家公司!
  5. 如何只用2GB内存从20/40/80亿个整数中找到出现次数最多的数
  6. Google MapReduce有啥巧妙优化?
  7. spring boot实战(第二篇)事件监听
  8. 理解Maven中的SNAPSHOT版本和正式版本
  9. NanoHttpd源码分析
  10. 解决springdatajpa 在解析实体类的字段时候驼峰自动转为下划线问题