Skip to content

Instantly share code, notes, and snippets.

@tkissing
Created January 7, 2015 18:14
Show Gist options
  • Save tkissing/0a642811a783ad0e09be to your computer and use it in GitHub Desktop.
Save tkissing/0a642811a783ad0e09be to your computer and use it in GitHub Desktop.
$.Deferred vs new Promise vs Callbacks - be careful you are not rebuilding the hell
// consider the following code
function getInfoDef() {
var result = {something: 'static'};
var def = $.Deferred();
$.ajax('/some-url').then(function(data) {
result.also = data.dynamic;
def.resolve(result);
}).fail(def.reject.bind(def));
return def.promise();
}
// if you are like me (half a year ago) you probably think this is just fine
// however, lets rewrite the same using ES6 Promises
function getInfoES6() {
return new Promise(function(resolve, reject) {
var result = {something: 'static'};
$.ajax('/some-url').then(function(data) {
result.also = data.dynamic;
resolve(result);
}).fail(reject);
});
}
// notice the extra level of indentation?
// does it remind you of callback hell?
// that's because it still is the same inversion control
function getInfoCB(callback) {
var result = {something: 'static'};
$.ajax('/some-url').then(function(data) {
result.also = data.dynamic;
callback(null, result);
}).fail(callback);
});
}
// this is how you should do it
function createThingy(remoteData) {
return {
something: 'static',
also: remoteData.dynamic
}
}
function getInfo() {
return $.ajax('/some-url').then(createThingy);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment