Ever wanted to write a JavaScript function that makes a HTTP request and then returns the results? Sounds simple, but the “and then” part of that sentence includes a lot of complexity. That is because when you make an HTTP request — it is performed asynchronously. This applies to jQuery AJAx, fetch, Axios, Nodes’s HTTPS module, etc. I’m not going to cover callbacks and promises. I want to ask you to forget about all that and learn two rules. With those rules, and a modern JavaScript runtime, you can write a function that solves the requirement I gave before in a few, highly readable lines, using async/ await.
I say highly-readable because what I love about async/ await is that you can read the code and get a much easier sense of what is going on. Instead of understanding then/when/catch/error/whatever, you see the request on one line and on the next line you see what is done with it.
In this post, I’m going to give you two basic rules of async/ await and some practical examples of their use. It’s a hard to explain this concept, but the code is short and readable, so you should be comfortable, when you’re done to start experimenting with
Source: https://managewp.org/articles/18051/two-rules-of-javascript-async-await
source https://williechiu40.wordpress.com/2018/11/01/two-rules-of-javascript-async-await/
No comments:
Post a Comment