Reputation: 824
I am trying to run a method that logs into facebook. The success callback of the login requests the current user's id, their events, their friends list and then runs through the friends list and requests the events for each of their friends and compares each friend's list of events with the current user's events.
The reason I run this as many separate requests is that it seemed more efficient to break it up so I wouldn't get such a huge blob of data all at once and choke up my app. Now I am not so sure.
I would like to get some advice on whether I should just make one big ajax request to get all the data, or whether I should break it up into smaller calls.
And if I should break it up into smaller calls, could I get some advice on the best way to do so? For example, should I chain them all as callbacks to each other?
It seems like the way forward is: 1. Get the user's id
Get the user's event list AND get the user's friend list could be executed independently and not have to be chained together
Get the user's friend list (as a callback to step 2 - after event list and friend list has been received)
Run the user's events vs their friend's events for each friend (as a callback to step 3)
(Sorry about the dodgy formatting - I tried wrestling with the code formatting but for some reason, it just didn't want to work today :( )
function collectFriendsRankedByCommonEvents(){
var myId;
var eventComparisonData = [];
var myData;
var myFriendsList;
//login with permission to userEvents, Friendslist and friend's events
FB.login(function(response){
if(response.status == 'connected'){
FB.api('/me', function(response) { myId = response['id'] });
FB.api((myId + '?fields=id,events'), 'GET', function(response){ myData = response })
FB.api((myId + '?fields=id,friends'), 'GET', function(response){ myFriendsList = response })
for(i=0; i < myFriendsList.length; i++){
var thisFriendId = myFriendsList[i]
var thisFriendData; //call to API to request friend's event data
var comparisonWithThisFriend = compareFriendEventsWithMe(myData, thisFriendData);
}
eventComparisonData.push(comparisonWithThisFriend);
} else { console.log('couldn\'t connect to facebook') }
},
{scope: 'user_friends, friends_events'}
);
//to iterative rendering method
}
Upvotes: 0
Views: 128
Reputation: 6572
In most cases you're best to do as few HTTP requests as possible. In any app an HTTP request is expensive and the weakest point of failure (consider mobile environment with fluctuating network connection) so if you can, just do everything in one request. It also makes your code more maintainable as it avoids callback chaining.
Unless you're receiving a multi-megabyte response, this shouldn't impact on performance. If you find that parsing the response does take time, you can use a Web Worker; this moves the parsing task to the background, freeing up the main thread so you can show feedback while its processing.
Upvotes: 1