简体   繁体   中英

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

I've never written a promise before but I feel like this code communicates my intent.

Question: How can I asynchronously fire off matchData() and countData() in the init block, after my http request has been completed, transformed and returned.

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

  }); 
}

You don't need to create you own promise using $q as $http method does return a promise by default, you could utilize that by calling .then method on it.

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(){...});
      });
}

Code

You could call the promise method just by doing .then on that method.

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

Yes $http returns a promise but doesn't necessarily get it back into your init method for your count and match function. Here is a solution using $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);
   */
})
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM