【问题标题】:AngularJS : Seqential Promise chainAngularJS:顺序承诺链
【发布时间】:2026-01-12 12:30:02
【问题描述】:

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

【问题讨论】:

    标签: javascript angularjs promise angular-promise


    【解决方案1】:

    您需要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);
    

    【讨论】: