Async and await
We have seen that the JavaScript runtime is single threaded and will push any asynchronous calls onto a particular queue within its memory, to be executed later. Using Promises helps us to structure our code to ensure that we only execute a particular section of code once the asynchronous call has completed. We still need to bear in mind, however, that the JavaScript runtime will continue to process our code line by line. This quirk of the language can often lead to weird results, or unwanted errors, if we do not take care when writing code that will be executed asynchronously.
Oftentimes, however, we need to make a series of calls to one asynchronous function after another. In these cases, it would actually be far better if we could pause the execution of our code until the asynchronous code completes. This is what the async
and await
keywords can do for us. In this section of the chapter, we will explore how to mark functions with the async
keyword, in order...