How to chain a variable number of promises in Q, in order?

There’s a nice clean way to to this with [].reduce. var chain = itemsToProcess.reduce(function (previous, item) { return previous.then(function (previousValue) { // do what you want with previous value // return your async operation return Q.delay(100); }) }, Q.resolve(/* set the first “previousValue” here */)); chain.then(function (lastResult) { // … }); reduce iterates through the … Read more

AngularJS $q. Deferred queue

Don’t use a queue and that boolean flag, just have one variable storing a promise representing all uploads. Also, your upload function should not take a Deferred object to resolve as an argument, but simply return a new promise. Then the addAnUpload becomes as simple as var allUploads = $q.when(); // init with resolved promise … Read more

Promises: Repeat operation until it succeeds?

All the answers here are really complicated in my opinion. Kos has the right idea but you can shorten the code by writing more idiomatic promise code: function retry(operation, delay) { return operation().catch(function(reason) { return Q.delay(delay).then(retry.bind(null, operation, delay * 2)); }); } And with comments: function retry(operation, delay) { return operation(). // run the operation … Read more

How do I sequentially chain promises with angularjs $q?

Redgeoff, your own answer is the way I used to translate an array into a chained series of promises. The emergent de facto pattern is as follows : function doAsyncSeries(arr) { return arr.reduce(function (promise, item) { return promise.then(function(result) { return doSomethingAsync(result, item); }); }, $q.when(initialValue)); } //then var items = [‘x’, ‘y’, ‘z’]; doAsyncSeries(items).then(…); Notes: … Read more