Skip to content

Instantly share code, notes, and snippets.

@pmcelhaney
Created July 10, 2012 17:57
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save pmcelhaney/3085144 to your computer and use it in GitHub Desktop.
createPromise() -- use promises with libraries that only support callback arguments
var createPromise = function (wrapper) {
var deferred = $.Deferred();
wrapper(
function () { deferred.resolve.apply(deferred, arguments); },
function () { deferred.reject.apply(deferred, arguments); }
);
return deferred.promise();
}
// USAGE:
// Say you have some old library that has success and fail callbacks rather than promises.
var asyncCalculator = {
add: function (a, b, success, fail) {
setTimeout(function () {
var result = a + b;
if (typeof result === 'number') {
if(success) success(result);
} else {
if (fail) fail();
}
}, 1000);
}
};
// The API expects you to pass two callback functions, one for success and one for failure
asyncCalculator.add(
5,
10,
function (result) { console.log('[callback] the sum is ' + result); },
function () { console.log('[callback] could not add'); }
);
// We would prefer the function to return a promise.
var adding = asyncCalculator.add(5, 10); // <--- This doesn't work (adding is undefined).
// So wrap the call in createPromise(). It's a little extra boilerplate, but it works.
var adding = createPromise(function (success, fail) {
asyncCalculator.add(5, 10, success, fail);
});
// Now we can pass around the promise and do whatever we like with it
adding.then(function (result) {
console.log('[promise] the sum is ' + result);
}, function () {
console.log('[promise] could not add');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment