Skip to content

Instantly share code, notes, and snippets.

@bguthrie
Created November 21, 2011 10:44
Show Gist options
  • Save bguthrie/1382285 to your computer and use it in GitHub Desktop.
Save bguthrie/1382285 to your computer and use it in GitHub Desktop.
A wrapper that applies a transform to jQuery.Deferred objects.
// Low level helper function for calling some API.
function callAPI(path, params) {
return $.get("/api/url" + path, params);
}
// High-level semantic function for retrieving widgets. Leverages the underlying
// API function but itself returns a promise.
function getAllWidgets(filter) {
var apiCall = callAPI("/widgets", $.extend(filter, { foo: "bar" }));
return redefer(apiCall, function(response) {
return response["outer"]["inner"]["widgets"];
});
}
// Accepts a promise and a transformation function and returns a new
// Deferred that resolves with the result of the transformation applied.
function redefer(promise, fn) {
var def = $.Deferred();
promise.then(function() {
def.resolve(fn(arguments));
});
return def;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment