1

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!

realph
  • 4,481
  • 13
  • 49
  • 104

1 Answers1

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'
    })
}
Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299
  • Nothing seems to be getting returned now. Any idea why this might be? No errors in the console either. P.S. I fixed the `function (resp)` typo on line 4. – realph Sep 05 '15 at 22:51