将响应传递给$q承诺的第二个then

Pass response to the 2nd `then` of a $q promise

本文关键字:承诺 第二个 then 响应      更新时间:2023-09-26

看一下这个简单的例子:

function colorPromise() {
  return $q.when({data:['blue', 'green']})
}
function getColors() {
  return colorPromise().then(function(res) {
     console.log('getColors', res)
     // do something with res
  };
}
function testGetColors() {
  getColors().then(function(res) {
    if (angular.equals(res, {data:['blue', 'green']})) {
      console.log('passes')
    }
  });
}

砰砰作响:http://plnkr.co/edit/LHgTeL9sDs7jyoS7MJTq?p=preview
本例中testGetColors函数中的resundefined

如何将res传递给$q承诺中的第二个then函数?

您需要返回res

function getColors() {
  return colorPromise().then(function(res) {
     console.log('getColors', res)
     return res; // here
  };
}

通过在您的第一个then .:

function getColors() {
  return colorPromise().then(function(res) {
     console.log('getColors', res)
     // do something with res
     return res; //<---
  };
}

.then返回承诺本身。如果您传递给它的function返回了一个非承诺值,则该承诺将立即用该返回值解决(这就是在您的情况下发生的情况,因为您的函数返回undefined(什么都没有))。请注意,您也可以在then -函数中返回一个承诺,以使then -promise成为该承诺。

您必须在getColors函数中执行return res,参见此plunkr