Waiting for Promises in a Loop

By Dave Ceddia Comment

Promises in a Loop

Need to run a series of HTTP calls, and wait for them all to complete? Use $q.all.

This won’t work:

for(var i = 0; i < 5; i++) {
	$http.get('/data' + i);
// At this point, all the requests will have fired...
// But probabaly, none of them have finished

Do this instead:

var promises = [];
for(var i = 0; i < 5; i++) {
	var promise = $http.get('/data' + i);

Run the promsies in order (not in parallel)

When you queue up promises like above, they all start at the same time. But what if you want them to run in the order you called them?

You can build up a chain of promises:

var chain = $q.when();
for(var i = 0; i < 5; i++) {
	chain = chain.then(function() {
		return $http.get('/data' + i);

// This is the same as:
chain = $q.when();
chain.then(function() {
			return $http.get('/data1');
		}).then(function() {
			return $http.get('/data2');
		}).then(function() {
			return $http.get('/data3');
		}).then(function() {
			return $http.get('/data4');
		}).then(function() {
			return $http.get('/data5');

$q.when is used to kick off the chain with a resolved promise.

Learning React can be a struggle -- so many libraries and tools!
My advice? Ignore all of them :)
For a step-by-step approach, read my book Pure React.

Loved it! Very well written and put together. Love that you focused only on React. Wish I had stumbled onto your book first before I messed around with all those scary "boilerplate" projects.
β€” John Lyon-Smith
comments powered by Disqus