AngularJS:顺序承诺链

时间:2014-09-17 15:02:50

标签: javascript angularjs promise angular-promise

功能one将值传递给two,然后two将值传递给three。这些功能中的任何一个都可能需要任何时间来返回数据。如何让他们等待价值而不是向前冲并打印undefined

var deferred = $q.defer();

var one = function (msg) {
  $timeout(function () {
    console.log(msg);
    return "pass this to two";
  }, 2000);
};

var two = function (msg) {
  console.log(msg);
  return "pass this to three";
};

var three = function (msg) {
  console.log(msg);
};

deferred.promise
  .then(one)
  .then(two)
  .then(three);

deferred.resolve("pass this to one");

1 个答案:

答案 0 :(得分:3)

您需要 return来自执行异步的每个功能的承诺。

在您的情况下,您的one函数返回undefined,而它需要返回您在超时后为"pass this to two"值创建的承诺:

function one (msg) {
  return $timeout(function () {
//^^^^^^
    console.log(msg);
    return "pass this to two";
  }, 2000);
}

顺便说一下,这条链不是使用var deferred = $q.defer();,而是更好地写成:

one("pass this to one")
  .then(two)
  .then(three);