Skip to content

Instantly share code, notes, and snippets.

@slavafomin
Last active April 4, 2020 04:29
Show Gist options
  • Star 16 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save slavafomin/8ee69f447765bc5c5e19 to your computer and use it in GitHub Desktop.
Save slavafomin/8ee69f447765bc5c5e19 to your computer and use it in GitHub Desktop.
Loop promises in Angular.js / Run list of actions sequantually

The provided example will allow you to do sequential requests to the server in Angular.js.

It will iterate all the items and call server for each item, however, if one request will fail, all sequential requests will be aborted.

If you need to call all requests no matter what, just replace promise.then() with promise.finally().

Cheers!

var listOfItems = [1, 2, 3, 4, 5];
// Creating an empty initial promise that always resolves itself.
var promise = $q.all([]);
// Iterating list of items.
angular.forEach(listOfItems, function (item) {
promise = promise.then(function () {
return $timeout(function () {
console.log('Item executed: ' + item);
}, 2000);
});
});
promise.finally(function () {
console.log('Chain finished!');
});
@aravindmp
Copy link

This was helpful.

@gsrdatta
Copy link

Nice.Working Well

@mikkoviitala
Copy link

👍

@sivapenumatsa
Copy link

Thanks helped a lot

@umdstu
Copy link

umdstu commented Mar 7, 2018

How would you go about nesting additional promises inside a loop inside the promise?

angular.forEach(listOfItems, function (item) {
  promise = promise.then(function () {
    return $timeout(function () {
      angular.forEach(listOfItems, function (item) {
         promise = promise.then(function () {
            return $timeout(function () {
               console.log('Item executed: ' + item);
            }, 2000);
        });
     });
    }, 2000);
  });

  /* have this guy wait until the above are finished */
  promise = promise.then(function () {
    return $timeout(function () {
      angular.forEach(listOfItems, function (item) {
         promise = promise.then(function () {
            return $timeout(function () {
               console.log('Item executed: ' + item);
            }, 2000);
        });
     });
    }, 2000);
  });
});

@klusinyan
Copy link

Thank you for sharing this solution. Spent whole day to find an elegant solution, finally got it!

Cheers.
Karen

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment