Strategies for Handling Asynchronous Information
Learn how to handle asynchronous information using promises in Angular.
We'll cover the following
We manage data asynchronously in different forms, such as consuming data from a back-end API or reading contents from the local filesystem. Consuming information from an API is a typical operation in our daily development workflow. We consume data over HTTP all the time, such as when authenticating users by sending out credentials to an authentication service. We also use HTTP when fetching the latest tweets in our favorite Twitter widget. Modern mobile devices have introduced a unique way of consuming remote services. They defer requests and response consumption until mobile connectivity is available. Responsivity and availability have become a big deal.
Although internet connections are high-speed nowadays, response time is always involved when serving such information. Therefore, as we will see in the following sections, we put mechanisms in place to transparently handle states in our applications for the end user.
Shifting from callback hell to promises
Sometimes, we might need to build functionalities in our application that change its state asynchronously once some time has elapsed. We must introduce code patterns such as the callback pattern to handle this deferred change in the application state.
In a callback, the function that triggers asynchronous action accepts another function as a parameter. The function is called when the asynchronous operation has been completed. Let’s see how to use a callback through an example:
First, run the following Angular CLI command to create a new Angular application:
Note: The command below is for creating an Angular application on the local machine using the Angular CLI.
Get hands-on with 1200+ tech skills courses.