将响应传递给$ q promise的第二个`then`

时间:2015-10-08 08:28:06

标签: javascript angularjs q

看看这个简单的例子:

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

Plunker:http://plnkr.co/edit/LHgTeL9sDs7jyoS7MJTq?p=preview
在此示例中,res函数中的testGetColorsundefined

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

3 个答案:

答案 0 :(得分:5)

您需要返回res

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

答案 1 :(得分:1)

将其返回到您的第一个then。:

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

     return res; //<---
  };
}

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

答案 2 :(得分:1)

您必须在return res函数中执行getColors,请参阅this plunkr