I want to chain some promises that are returned by services. This works, as long as some of the methods that return the promises, doesn't require additional parameters. This is my example:
var first = function() {
var d = $q.defer();
$timeout(function() {
d.resolve("first resolved")
}, 100)
return d.promise;
};
var second = function(val) {
console.log("value of val: ", val);
var d = $q.defer();
$timeout(function() {
d.resolve("second resolved")
}, 200)
return d.promise;
};
first().then(second).then(function(value) {
console.log("all resolved", value);
});
This works as expected. But what if my service second
needs an additional parameter val
to do it's job? With the method above the value of val
is "first resolved"
, because it get's the resolved value from first
.
Is there any way around, without nesting anonymous functions like this:
first().then(function() {
return second("foobar").then(function(value) {
console.log("all resolved", value);
});
});
I was thinking about using $q.all
, but IMHO you can't specify an order for your promises.
$timeout
already returns a promise, no need for a$q.defer
there – Hermit$q.defer
– Hugh.then
it for the extra processing and return that... can't make a judgement about code I haven't seen but it still sounds like the deferred anti pattern. You only need$q.defer
when working against a callback API when promisifying it. – Hermit