Last active
August 29, 2015 14:16
-
-
Save zhannes/964861f000e1325907ab to your computer and use it in GitHub Desktop.
callback vs dfd
This file contains 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
// old way, plan to pass a func | |
function doAsyncStuff(callback){ | |
// do stuff, then call the function that was passed | |
setTimeout(callback,2000); | |
} | |
// calling it | |
doAsyncStuff(function(){ | |
console.log('internet website') | |
}) | |
///////////////////////// | |
// new way | |
// assumes Q.js has been loaded and available as Q (could also use jQuery) | |
function doMoreAsync(){ | |
var dfd = Q.defer(); | |
// in 2000 secs, *resolve* promise with data | |
setTimeout(function(){ | |
dfd.resolve({foo: 'bar'}) | |
// or reject for whatever reason | |
// dfd.reject({error: 'fail'}) | |
},2000) | |
// return promise | |
return dfd.promise | |
} | |
/* async func returns a promise object. Promises have a method named 'then' */ | |
doMoreAsync() | |
.then(function(data){ | |
// do stuff with the data | |
console.log('the promise was resolved', data) | |
}).fail(function(error){ | |
// handle rejected promise | |
console.log('promise rejected, error callback', error) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment