Search code examples
javascriptangularjsapisendasynchronousrequest

How to pick latest api call when multiple api call were made


We ran into a problem when multiple API calls were made repeatedly the UI sometimes renders the wrong data.

Example:

onPageLoad event I have 5 API calls and we have date picker from where we can select the dates. When user tries to change the date selector all the 5 API calls will be made to refresh the data suppose initially I selected last day and the page is loaded and now I changed to last week then month and then back to last day now there 15 async API calls were made and in the UI we are rendering whichever API call arrived the lately(because of Asynchronous behaviour in JS). Is there any mechanism in angular to control this behavior.

Expected:

I want to show only the latest API call data in the UI(irrespective when the promise gets resolved) in the above example I want to show only last day's data.


Solution

  • With this code any previous api call will be rejected. This means only the last call will resolve.

    var timeout;
    
    function callApi() {
        // Cancel any previous api call:
        timeout && timeout.resolve();
    
        // Create a new timeout:
        timeout = $q.defer();
    
        // Make the api call, passing in the timeout:
        return $http.get('/api', {timeout: timeout.promise});
    }