Skip to content

Instantly share code, notes, and snippets.

@rmurphey
Created September 17, 2012 00:58
Show Gist options
  • Save rmurphey/3735030 to your computer and use it in GitHub Desktop.
Save rmurphey/3735030 to your computer and use it in GitHub Desktop.
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);
}
}
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);
}
@ralphholzmann
Copy link

+1 to what @rmurphey said. This is the difference between refactoring and rewriting. Refactoring doesn't change your external API, it only changes the internals. Rewrites have the freedom to change the API.

@ryanflorence
Copy link

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment