-
-
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); | |
} |
@rpflorence I don't disagree, but for the sake of what I'm trying to demonstrate, I'm not trying to show "how to make this the ideal piece of code" -- I'm trying instead to show a specific thing: how to use a deferred to rewrite the function without changing how it works. Returning a dfd would require rewriting code that consumes this function, which is not necessarily desirable. Writing from scratch, sure, I'd take the approach you outlined -- well, honestly, I'd use a framework of some sort that would likely hide a lot of this -- but this example (for a talk I will be giving later this year) is focused more on rewriting existing code.
+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.
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.
Don't mix paradigms. You're bringing the inflexibility of callback soup right back into your API with
getSomeThings
taking a callback. Just return the deferred :)This way I can add error callbacks, or do what I need with the data, or mix it with some other deferred:
Also, what is the point of returning
data.people
etc. in the done handlers?