Click here to Skip to main content
15,887,415 members
Articles / All Topics

Waiting for Promises in a Loop

Rate me:
Please Sign up or sign in to vote.
5.00/5 (2 votes)
21 Jan 2016CPOL 12.6K  
Waiting for Promises in a Loop

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:

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

Do this instead:

JavaScript
var promises = [];
for(var i = 0; i < 5; i++) {
	var promise = $http.get('/data' + i);
	promises.push(promise);
}
$q.all(promises).then(doSomethingAfterAllRequests);

Run the Promises In Order (Not In Parallel)

When you queue up promises like the 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:

JavaScript
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.

Waiting for Promises in a Loop was originally published by Dave Ceddia at Angularity on January 21, 2016.

This article was originally posted at https://daveceddia.com/feed.xml

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
Dave is a Software Engineer in the Boston area and writes about AngularJS and other JavaScript things over at daveceddia.com

Comments and Discussions

 
-- There are no messages in this forum --