Created
January 3, 2020 14:53
-
-
Save montanaflynn/f986fc4bafdf5de6197b6115de08f66b to your computer and use it in GitHub Desktop.
Example of providing error-first callback mechanism by default but also a chained .promise() method
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
// Example from https://nickmeldrum.com/blog/intriguing-reason-node-not-promises-by-default | |
const doS3GetObject = params => { | |
if (someErrorHappens) { | |
throw new Error('uh oh, we borked') | |
} | |
else { | |
return 'we done good' // imagine we actually did the work! | |
} | |
} | |
const s3 = { | |
getObject: (params, callback) => { | |
if (callback) { | |
try { | |
callback(null, doS3GetObject(params)) | |
} | |
catch (e) { | |
callback(e) | |
} | |
} | |
return { | |
promise: () => new Promise((resolve, reject) => { | |
try { | |
resolve(doS3GetObject(params)); | |
} catch (e) { | |
reject(e) | |
} | |
}), | |
} | |
}, | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment