0

Apolgies if my question is basic - I have spent a good amount of time trying to understand callbacks to resolve this myself, but I am stuck! I have also reviewed other similar questions, but can't apply what I learned to this.

I am trying to modify the standard Ionic tutorial. This service part of the application is intended to return an array of friend data to populate a dropdown.

In the original sample, the data is manually loaded with hardcoded values as an example. You can see that commented out towards the bottom.

My question is how do I make the return of the overall function wait for the completion of my asynchronous facebook call which brings back real data in place of the dummy data.

Thanks so much!

John

angular.module('starter.services', [])

.factory('Friends', function() {

  function friendsFunction() {

    //Async FB API call to return friends of user
    FB.api('/me/friends', function (response) {

      var fbFriendData = [];

      //Load friends into an array
      for (var i = 0; i < response.data.length; i++) {

        fbFriendData.push({
          id: i,
          fbid: response.data[i].id,
          name: response.data[i].name
      });

      }

      return fbFriendData;

    });

  }

  var friends = friendsFunction();

  //friends = [
  //  {id: 0, name: 'KJ'},
  //  {id: 1, name: 'Your Mum'},
  //  {id: 2, name: 'Nikki B'},
  //  {id: 3, name: 'Jesus'}
  //];

  return {
    all: function() {
      return friends;
    },
    get: function(friendId) {
      // Simple index lookup
      return friends[friendId];
    }
  }

});
John Furneaux
  • 156
  • 1
  • 7
  • In a word, you can't. An async function is async. Your function will return long before the actual results are even available. You MUST learn to program in an async fashion. The results will ONLY be delivered in a callback, not in a return value. I'd suggest you read and study [this answer](http://stackoverflow.com/a/14220323/816620) which shows you the options. – jfriend00 Nov 15 '14 at 05:57
  • That's a great link to help me, I hadn't found it with my search terms, many thanks. – John Furneaux Nov 15 '14 at 21:14

0 Answers0