AngularJS : Seqential Promise chain

AngularJS : Seqential Promise chain

本文关键字:chain Promise Seqential AngularJS      更新时间:2023-09-26

函数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");

您需要return从每个执行异步操作的函数中获得一个promise

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

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