Search code examples
javascriptangularjshttpsettimeout

AngularJS $q.all - wait between http calls


So I have a situation where I need to perform a bunch of http calls, then once they are complete, continue on to the next step in the process.

Below is the code which does this and works fine.

However, I now need to wait a few seconds between each of the http calls. Is there a way to pass in a timeout with my current set up, or will it involve a good bit of refactoring?

Can post more code if needs be. I have tried passing in a timeout config varable into the http call, however, they still get fired at the same time.

Any advice would be great.

Code

 var allThings = array.map(function(object) {
     var singleThingPromise = getFile(object.id);
     return singleThingPromise;
 });
 $q.all(allThings).then(function() {
     deferred.resolve('Finished');
 }, function(error) {
     deferred.reject(error);
 });

Solution

  • Instead of using $q.all, you might want to perform sequential calls one on success of previous and probably with use of $timeout. Maybe you could build a recursive function.

    Something like this..

    function performSequentialCalls (index) {
      if(angular.isUndefined(array[index])) {
        return;
      }
      getFile(array[index].id).then(function() {
        $timeout(function() {
          performSequentialCalls(index + 1)
        }, 1000) // waiting 1 sec after each call
      })
    }
    

    Inject required stuff properly. This assumes array to contain objects with ids using which you perform API calls. Also assumes that you are using $http. If using $resource, add $promise accordingly.

    Hope that helps a bit!