Created
November 21, 2011 10:44
-
-
Save bguthrie/1382285 to your computer and use it in GitHub Desktop.
A wrapper that applies a transform to jQuery.Deferred objects.
This file contains hidden or 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
// 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"]; | |
}); | |
} |
This file contains hidden or 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
// 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