Skip to content

Instantly share code, notes, and snippets.

@dalgard
Last active August 29, 2015 13:56
Show Gist options
  • Save dalgard/9091289 to your computer and use it in GitHub Desktop.
Save dalgard/9091289 to your computer and use it in GitHub Desktop.
Module/function boilerplate using promises
/*
Module boilerplate (jQuery)
- Pass in a callback OR a promise
- Always returns a promise
*/
function getStuff(arg, d) {
var callback = d, // Save possible callback
is_promise = d && d.resolve; // Check whether d is a promise
// If a promise was not passed in, create a new deferred
if (!is_promise) d = $.Deferred();
try {
// Some (possibly) asynchronous operation
asyncGet(arg, function (stuff) {
// If using a classic callback, pass the result to it
if (typeof callback === "function") callback(stuff);
// Resolve the module deferred with the result
d.resolve(stuff);
});
}
catch (err) {
// Something horribly wrong, reject the deferred with the error
d.reject(err);
}
// Return the locked down version of the deferred (aka. promise)
return d.promise();
}
/*
Example use
*/
var stuff_promise = getStuff("my-stuff");
stuff_promise.then(
function (stuff) { ... },
function (err) { ... }
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment