Skip to content

Instantly share code, notes, and snippets.

@jonjaques
Last active December 17, 2015 04:19
Show Gist options
  • Save jonjaques/5549597 to your computer and use it in GitHub Desktop.
Save jonjaques/5549597 to your computer and use it in GitHub Desktop.
Abstracting async ops with promises
// So let's say you have an async operation that doesn't
// use a jQuery-ajax method. In my example, I'll use a call
// to the FB API, which just takes a callback function
// which gets called with a ```resp``` object.
FB.api('/platform', function(resp) {
if (resp.data) {
success();
} else if (resp.error) {
error();
}
});
// We can do better.
function getPage(page) {
var dfd = $.Deferred();
FB.api(page, handleResp(dfd));
return dfd.promise();
}
function handleResp(dfd) {
return function(resp) {
if (resp.data) {
dfd.resolve(resp.data);
} else if (resp.error) {
dfd.reject(resp.error);
} else {
dfd.reject("Something went wrong!");
}
}
}
// Now we can use API methods just like Ajax calls!
getPage('/platform')
.done(function(data) {
doStuff();
})
.fail(function(error) {
handleError();
});
// And handle multiple async requests, and be
// notified when they're all done
$.when(getPage('/platform'), getPage('/otherPage'))
.done(function(platform, otherPage) {
// do stuff
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment