patternjavascriptMinor
Requesting Resources Until Exhaustion
Viewed 0 times
resourcesrequestingexhaustionuntil
Problem
When an API has a 'next' feature, I use the following pattern to obtain all the results:
Is there a better way to go about this?
/** Obtains a list of channels followed by a user */
function get_follows(username, callback) {
var channels = [];
function handler(data) {
if (!data || data.follows.length == 0) {
callback(channels);
return;
}
for (var i = 0; i < data.follows.length; i++)
channels.push(data.follows[i].channel);
JSON.load(data._links.next, handler);
}
var url = "https://api.twitch.tv/kraken/users/"+username+"/follows/channels?limit=75&offset=0&on_site=1";
JSON.load(url, handler);
}Is there a better way to go about this?
Solution
I like your code, and would use it myself, some thoughts:
-
I assume you declare
-
lowerCamelCase is good for you,
-
Comparing to
From a design perspective, you are circumventing the paging system, are you sure you always need every single channel? I hope you at least cache the retrieved information.
-
I assume you declare
url next to JSON.load because you want to declare it close to where you use it. I would still recommend using 1 comma separated list of variables on the top.-
lowerCamelCase is good for you,
get_follows -> getFollows -> getFollowedChannels ?-
Comparing to
0 should be done with ===, if you do it for the length of an array I would go with a falsey comparison: if (!data || !data.follows.length) {From a design perspective, you are circumventing the paging system, are you sure you always need every single channel? I hope you at least cache the retrieved information.
Context
StackExchange Code Review Q#42878, answer score: 5
Revisions (0)
No revisions yet.