Created
September 17, 2012 00:58
-
-
Save rmurphey/3735030 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function getSomeThings(callback) { | |
var completed = 0; | |
var people, tasks; | |
$.ajax('/data/people.json', { | |
dataType: 'json', | |
success: function(data) { | |
completed++; | |
people = data.people; | |
onFinished(); | |
} | |
}); | |
$.ajax('/data/tasks.json', { | |
dataType: 'json', | |
success: function(data) { | |
completed++; | |
tasks = data.tasks; | |
onFinished(); | |
} | |
}); | |
function onFinished() { | |
if (completed !== 2) { return; } | |
callback(people, tasks); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function getSomeThings(callback) { | |
var peopleRequest = $.getJSON('/data/people.json').then(function(data) { | |
return data.people; | |
}); | |
var tasksRequest = $.getJSON('/data/tasks.json').then(function(data) { | |
return data.tasks; | |
}); | |
$.when(peopleRequest, tasksRequest).then(callback); | |
} | |
function getSomeThings(callback) { | |
var reqs = $.map([ 'people', 'tasks' ], function(idx, req) { | |
return $.getJSON('/data/' + req + '.json').then(function(data) { | |
return data[req]; | |
}); | |
}); | |
$.when.apply($, reqs).then(callback); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Agreed. I didn't know the context of the code samples.
I'd still return the $.when though, so future consumers can get the benefits of deferreds.