I say highly-readable because what I love about
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
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 this new API.
Rule One Of Aysnc/ Await
You Must Use The
await Keyword Only In Closure That Is Declared With The
Inside of this closure, we may use
async keyword is used when declaring the function.
The await keyword is the real magic of async/ await. Before you can use it — see rule two — you must know rule one. Rule one shows us how to create closure that can use the
await keyword. How? We type the
async keyword before a function.
Got that? That’s rule one, you’ll see examples when I explain rule two under the next heading.
Inside Of An
async Closure, If Another
async Function Is called With The
await Keyword, The Next Line Will Not Run Until That Line's Promise Has Resolved.
In this example, line 7 will not run until the Promise created on line 6 has been resolved or rejected.
In this example, I’m using the fetch API, which creates a promise. That’s all been made invisible by using await. Instead of using a
then() callback, I'm just awaiting the result of the function.
Notice that the before I declare the function I used the
async keyword. That's another example of how rule one works. This function says
async in front of it, so I can use
await inside of it.
You can use this asynchronous function only inside of another asynchronous function. For example:
Inside of an
async function, we can
await the results of an
For a more complete example, here is a more abstract version of
getMostRecentPost() that works with any site and then another function that calls it twice and after awaiting those results, returns both posts.
async function calling another
async function using
The new fetch API uses promises and a new syntax for making AJAX requests. fetch is much cleaner than XMLHttpRequest.
That’s The Whole API! Use It!
In this post, you learned two rules of
Want to learn more? I’ll leave you with a Wes Bos video:
Originally published at Josh Pollock.