Unit 7. Working asynchronously
JavaScript has always been an asynchronous language. That makes it a perfect language for creating rich applications, because it can handle many concurrent tasks without locking the interface. But until recently, there hasn’t been much first-class support for its asynchronous nature other than being able to pass around functions that can be invoked at a later time. That has all changed. JavaScript now has first-class support for promises, asynchronous functions, and soon, for observables.
Promises are objects that represent future values. They are more convenient to pass around than callbacks because, unlike callbacks, they don’t rely on timing. A promise will give a value right away if the value has already been retrieved, or can wait until the value is retrieved. With callbacks, if you are too late and the value has already been retrieved, your callback may not get invoked.
Promises, as we’ll soon see, also provide tools to make complex asynchronous calls easier and remove the need for callback hell.
It can be hard for people to wrap their heads around complex asynchronous interactions, which can lead to bugs. Blocking actions are much easier to think about, but are less efficient. Promises make complex asynchronous code easier to manage, but you still have to think asynchronously. But not with async functions. Async functions allow you to write your code as if it were a blocking operation.