Created
January 7, 2015 18:14
-
-
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
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
// 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