Creating an asynchronous service
We just created a service called MovieService
that synchronously calls the getMovies()
method to retrieve the collection of movies. As we are consuming an external source, such as a web API, to retrieve the collection of movies, our application has to wait until the server responds with the list of movies, as the getMovies
function is synchronous.
So we need to implement an asynchronous mechanism to retrieve the collection of movies. In such way, we can avoid making our application wait until the web API responds with the collection of movies. We can achieve this by using promises.
What is a Promise?
A Promise is a sincere assurance that an action will be performed. It calls back a function when the server responds with the result. We request an asynchronous service with a callback function to perform some operation and the service calls our callback function with either the result or with the error. You can read more about promises in Chapter 7, Asynchronous...