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.
Of course. First way:
first()
.then(function() {
return second("foobar");
})
.then(function(value) {
console.log("all resolved", value);
});
Second (much easier) way:
first()
.then(second.bind(null, "foobar"))
.then(function(value) {
console.log("all resolved", value);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With