Skip to content

Instantly share code, notes, and snippets.

@mightyguava
Created March 12, 2017 18:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mightyguava/750017bddc4c74b502f586621f37366f to your computer and use it in GitHub Desktop.
Save mightyguava/750017bddc4c74b502f586621f37366f to your computer and use it in GitHub Desktop.
Demystifying Async Programming in Javascript - fetchJson callbacks
// Suppose that we have a method fetchJson() that does GET requests and has an interface that looks
// like this, where callback is expected to take error as its first argument and the parsed response
// data as its second.
function fetchJson(url, callback) { ... }
fetchJson('/api/user/self', function(e, user) {
fetchJson('/api/interests?userId=' + user.id, function(e, interests) {
var recommendations = [];
interests.forEach(function () {
fetchJson('/api/recommendations?topic=' + interest, function(e, recommendation) {
recommendations.push(recommendation);
if (recommendations.length == interests.length) {
render(profile, interests, recommendations);
}
});
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment