Reputation: 6832
Got an issue with angularjs and some promises. For some reason, my services mix answers on queries, and while services are fixed I need to change my $q.all() to instead of running all promises asynchronously, run then in sequence.
Right now, it looks like this :
var promises = [p1, p2, p3];
$q.all(promises).then(function () {
// All promises are done
}).catch(function (exception) {
// An error occured.
});
Expected behaviour should be like p1.then(p2).then(p3);
, and order does not matter (since normally run async). Array lenght is variable.
Since $q is inspired by Q lib, I looked in Q documentation and found a sequence reference but couldn't make it work with $q.
Can anyone recommand an easy solution for such issue ?
I did tryed this promises.reduce($q.when, $q(initialVal));
but don't understand what initialVal refere to :(
Thanks for reading, and have a nice day.
Upvotes: 2
Views: 2523
Reputation: 447
If you already have promises, the asynchronous methods are already fired! You have to fire them one by one, so your array needs to contain functions that return promises rather than promise objects.
You can then go about it like this, which is clearer to me than the shortcut from Q you provided in your question:
var promiseReturningFunctions = [p1, p2, p3];
var queueEntryPoint = $q.defer();
// create a waiting queue
var queue = queueEntryPoint.promise;
// this queues up the asynchronous functions
promiseReturningFunctions.forEach(function (p) {
queue = queue.then(p);
});
// here we start processing the queue by resolving our queueEntryPoint
queueEntryPoint.resolve();
// we can now use queue.then(...) to do something after all promises in queue were resolved
queue.then(function () {
// All promises are done
}).catch(function (exception) {
// An error occured.
});
Upvotes: 6