23tux
23tux

Reputation: 14736

AngularJS : Pass additional parameters to chained promises

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.

Upvotes: 9

Views: 5547

Answers (1)

Razem
Razem

Reputation: 1441

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);
  });

Upvotes: 10

Related Questions