0

I'm working with Facebook Graph API using AngularJS. It has a function called FB.api(); which returns a response object containing some data. However, this is an async function. I'd like to know how to wait for this function to return before continuing with the rest of the script.

Consider the following code:

var data = [];
FB.api('/' + response.data[i].id + '/tags', 'GET', {}, function(response) {
for(var j = 0; j < response.data.length; j++) {
    var friend = {
        id: response.data[j].id,
        name: response.data[j].name
    };

    FB.api('/' + response.data[j].id + '/picture?width=200&height=200', 'GET', function(response) {
        friend.url = response.data.url;
    });

    $timeout(function() {
        data.push(friend);
    }, 3000);
}

});

I'm trying to build a function which returns a list of objects. I loop through the data and save the data that I need in an object. Inside the loop, I'm making another call to the async API function to get some additional data. However, this function doesn't return instantly, and hence the data response.data.url is never saved in friend object.

I have used Angular's &timeout service to simulate waiting for this function to return; however, this seems like a very hacky technique. Is there any way I can wait for all the functions to return before executing rest of the script?

Please try to suggest code examples if possible.

Rafay
  • 23,785
  • 4
  • 20
  • 27
  • 2
    Loops and async callbacks don't mix well. Perhaps you should look into this famous answer http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – elclanrs Jun 14 '16 at 07:24
  • you can use a recursive functions, for example – andyrandy Jun 14 '16 at 07:28

2 Answers2

1

You may see the link below, i think this is similar to your issue

Is there a possible way implementing Promise inside angular.foreach?

Community
  • 1
  • 1
nescafe
  • 187
  • 1
  • 3
  • 14
0

You should use async.each() instead of for() because for() don't wait for callback() here: https://www.npmjs.com/package/async#each

feeling
  • 25
  • 7