Search code examples
angularpromisecancellationtypescript2.1

How to cancel old promises?


A page of my Ionic 3 app make network calls and receive results in the shape of a promise. But some calls takes more time than others. In some cases the request A, which is made before request B, can take more time to response than request B.

For example, in a text query search, if the user triggers two subsequent requests with different parameters for the backend he can receive the response B before the response A. Then the view will show the second search result and then,after some time, the first search result, which is not the expected behavior. I always need to show the data of the last request.

How could I cancel a promise so that I aways shows the most recent data?


Solution

  • The way I handled the race condition of multiple requests is to add a timestamp onto the request as a query parameter or a header, which you then check again when you receive the response. If the timestamp isn't the most recent that has been processed already, just throw it out.