Created
November 3, 2016 19:58
-
-
Save selvagsz/843aa75b86d13915f04ceb839fc4919a to your computer and use it in GitHub Desktop.
Diff between native promise & $.Deferred promise chain
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
// Check the console logs by uncommenting the error throwing scenario also | |
function one() { | |
console.log('one') | |
throw new Error('error1') | |
} | |
function two() { | |
console.log('two') | |
} | |
function three() { | |
console.log('three') | |
} | |
function errorHandlerOne(err) { | |
console.log('Error1', err) | |
// throw err //uncomment this line to check error bubbling chain | |
} | |
function finalErrorHandler(err) { | |
console.log('Final Error', err) | |
} | |
// Synchronous | |
try { | |
console.log(`------- Synchronous flow -------`) | |
try { | |
one() | |
two() | |
} catch (e) { | |
errorHandlerOne(e) | |
} | |
three() | |
} catch (e) { | |
finalErrorHandler(e) | |
} | |
// Native Promises | |
let someAsync = () => { | |
return new Promise((resolve, reject) => { | |
setTimeout(function() { | |
console.log(`------- Native Promise Chain -------`) | |
resolve() | |
}, 500) | |
}) | |
} | |
someAsync() | |
.then(one) | |
.then(two) | |
.catch(errorHandlerOne) | |
.then(three) | |
.catch(finalErrorHandler) | |
// $.Deferred promise | |
function deferredAsync () { | |
let deferred = $.Deferred() | |
setTimeout(function() { | |
console.log(`------- $.Deferred Promise Chain -------`) | |
deferred.resolve() | |
}, 500) | |
return deferred | |
} | |
deferredAsync() | |
.then(one) | |
.then(two) | |
.fail(errorHandlerOne) | |
.then(three) | |
.fail(finalErrorHandler) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment