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.