Lesson 32. Async functions
After reading lesson 32, you will be able to
- Write asynchronous code using a synchronous syntax
- Use generators to write asynchronous code
- Use asynchronous functions to write asynchronous code
One of the reasons JavaScript can be hard to learn is because of its asynchronous nature. Asynchronous code is hard to think about, but it’s this asynchronous nature that makes JavaScript such a great language for the web. Web applications are full of asynchronous actions—from loading assets to handling user input. The purpose of asynchronous functions is to make it easy to write and think about asynchronous code.
Consider this
So far in this unit we’ve been dealing with promises, which have proven to be much more useful than traditional asynchronous code using callbacks. But when using promises you still have to think asynchronously, which is much harder to do than thinking synchronously. Languages like PHP or Ruby are synchronous, so operations that take time to complete are easier to think about, but they’re blocking. This means they halt the execution of any code and block everything else from happening until they finish. What if you could get the best of both worlds and write code that looks as if it’s blocking—making it easier to think about—but still operates asynchronously?