Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 662
23tux Avatar asked Jul 23 '14 11:07

23tux


1 Answers

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);
  });
like image 93
Razem Avatar answered Oct 17 '22 21:10

Razem