Skip to content

Instantly share code, notes, and snippets.

@alexcurtis
Last active December 13, 2015 18:08
Show Gist options
  • Save alexcurtis/4952689 to your computer and use it in GitHub Desktop.
Save alexcurtis/4952689 to your computer and use it in GitHub Desktop.
Refactoring with JQuery Promises
function GetPopularServices(id) {
var d = $.Deferred();
var popularServiceUrl = PopularServiceUrl(id);
$.getJSON(popularServiceUrl, {}, function (data) {
CreatePopularService(this, function(service) {
//...
//Resolve The Promise
d.resolve({ services: [service] });
});
}).error(function () { ShowErrorDialog(); });
return d.promise();
}
function GetCategoryServices(id) {
var d = $.Deferred();
var categoryServiceUrl = CategoryServiceUrl(id);
$.getJSON(categoryServiceUrl, {}, function (data) {
var services = [];
$(data).each(function () {
CreateService(this, function(service) {
//...
services.push(service);
});
//Resolve The Promise When Done
}).promise().done(function () { d.resolve({ services: services }); });
}).error(function () { ShowErrorDialog(); });
return d.promise();
}
function PostProcessService(service) {
//...
}
//Get Services For id
function GetServices(id) {
$.when(GetPopularServices(id), GetCategoryServices(id)).done(function (pop, cat) {
PostProcessService(pop);
PostProcessService(cat);
ShowResults();
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment