Angular: Return id From $http Inside Parent Functi

2019-08-07 09:23发布

问题:

This question already has an answer here:

  • How do I return the response from an asynchronous call? 35 answers

I'm not sure if I'm doing this right, but I've got a parent function returnPersonId() which uses $http to fetch an object and return that object's id.

function returnPersonId(n) {
  var q = 'http://api.themoviedb.org/3/search/person?api_key=' + apiKey + '&query=' + n;
  $http({ method: 'GET', url: q })
    .success(function (data, status, headers, config) {
      if (status == 200) {
        var person = data.results[0];
        var id = person.id;
        return id;
      }
    })
    .error(function (data, status, headers, config) {
      console.log('Error happened whilst getting the actor or actress.');
    })
}

Currently it's returning the id inside the success method. I'm not sure how to return the id to its parent function, so if I run the function I'm returned the id, like so:

returnPersonId('tom+hanks'); // returns 31

How would I go about doing this?

Any help is appreciated.

Thanks in advance!

回答1:

As callback function doesn't return a data from it you need to switch your code style to use promise pattern where you can easily return a data on success or on failure.

function returnPersonId(n) {
  var q = 'http://api.themoviedb.org/3/search/person?api_key=' + apiKey + '&query=' + n;
  return $http({ method: 'GET', url: q })
    .then(function (resp) {
      var data = res.data
      if (res.status == 200) {
        var person = data.results[0];
        var id = person.id;
        return id;
      }
    },function (error) {
      console.log('Error happened whilst getting the actor or actress.');
      return 'Error occured'
    })
}