Created
June 8, 2017 11:41
-
-
Save kochmaxence/478b63536c87d2aee0dd30a70042405b to your computer and use it in GitHub Desktop.
Why you should return in callback?
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
/** | |
* Note that you don't have a "return_err" in your console. | |
* But you have "noreturn_err". | |
* | |
* Even if you resolve/reject your promise, it's still a function that'll | |
* keep its execution until it is returned. | |
*/ | |
const log = tag => (...args) => console.log(tag, ...args); | |
const p = (tag, err) => new Promise((resolve, reject) => { | |
if (err) reject(err); // no return, it'll keep processing even if it's rejected/resolved. | |
console.log(tag, 'Shouldn\'t display if error'); | |
resolve(tag + ' resolved'); | |
}); | |
p('noreturn_noerr') | |
.then(log('noerr_then')) | |
.catch(log('noerr_catch')); | |
p('noreturn_err', new Error('error: no_return')) | |
.then(log('err_then')) | |
.catch(log('err_catch')); | |
const pR = (tag, err) => new Promise((resolve, reject) => { | |
if (err) return reject(err); // Promise is rejected and execution stops | |
console.log(tag, 'Shouldn\'t display if error'); | |
return resolve(tag + ' resolved'); | |
}); | |
pR('return_noerr') | |
.then(log('noerr_then')) | |
.catch(log('noerr_catch')); | |
pR('return_err', new Error('error: return')) | |
.then(log('err_then')) | |
.catch(log('err_catch')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment