AngularJS:将其他参数传递给链式承诺

时间:2014-07-23 11:52:49

标签: javascript angularjs promise angular-promise

我想链接一些由服务返回的promise。只要一些返回promise的方法不需要额外的参数,这就可以工作。这是我的例子:

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

这可以按预期工作。但是,如果我的服务second需要一个额外的参数val来完成它的工作呢?使用上述方法,val的值为"first resolved",因为它是first的已解析值。

有没有办法,没有嵌套这样的匿名函数:

first().then(function() {
  return second("foobar").then(function(value) {
    console.log("all resolved", value);
  });
});

我在考虑使用$q.all,但恕我直言,你无法为你的承诺指定订单。

1 个答案:

答案 0 :(得分:10)

当然。第一种方式:

first()
  .then(function() {
    return second("foobar");
  })
  .then(function(value) {
    console.log("all resolved", value);
  });

第二种(更容易)方式:

first()
  .then(second.bind(null, "foobar"))
  .then(function(value) {
    console.log("all resolved", value);
  });
相关问题