Angular $q 库在对 api 的 $http 请求成功后链接方法?

Angular $q library to chain methods after success of an $http request to api?

我以前从未写过承诺,但我觉得这段代码表达了我的意图。

问题: 在我的 http 请求完成、转换并返回后,如何在 init 块中异步触发 matchData()countData()

 function getLangData(langCode) {

    var url = "https://translate.google.com/translate_a/l?cb=JSON_CALLBACK";
      return $q(function(resolve, reject) {    
      $http.jsonp(url, {
        params: {...}
      })
        .success(function (translateAPIData) {
                 return translateAPIData.map(function(){...});
          });
        });

      });
  }

function init() {
  var promise = getLangData(languageCode);
  promise.then(function(mappedData) {
     matchData(mappedData);
  });
  promise.then(function(mappedData) {
     countData(mappedData);
  });  

  }); 
}

您不需要使用 $q 创建您自己的承诺,因为 $http 方法默认执行 return 承诺,您可以通过调用 .then 方法来利用它.

function getLangData(langCode) {

    var url = "https://translate.google.com/translate_a/l?cb=JSON_CALLBACK";
      //returned promise object from method
      return $http.jsonp(url, {
        params: {...}
      })
      .then(function (response) {
           var translateAPIData = response.data;
           return translateAPIData.map(function(){...});
      });
}

代码

您只需对该方法执行 .then 即可调用 promise 方法。

function init() {
  var promise = getLangData(languageCode);
  promise.then(function(mappedData) {
     matchData(mappedData);
     countData(mappedData);
  }); 
};

是的 $http returns 一个承诺,但不一定将它返回到您的计数和匹配函数的 init 方法中。这是使用 $q.

的解决方案
function getLangData(langCode) {

var url = "https://translate.google.com/translate_a/l?cb=JSON_CALLBACK";
var defer = $q.defer();

$http.jsonp(url, {
    params: {...}
  }).then(function (translateAPIData) {
      defer.resolve(translateAPIData.map(function(){...}));
  });

  return $q.promise;
}

function init() {

 getLangData(languageCode).then(function(mappedData) {
   //Do something with your data here.
   /*
   matchData(mappedData); 
   countData(mappedData);
   */
})
}