Created
October 31, 2017 19:10
-
-
Save amackintosh/71f22da271cb7ba2551e9d92068936e6 to your computer and use it in GitHub Desktop.
JavaScript Function that returns a Promise or Callback depending if a callback was specified
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
function myFunc(obj, callback) { // call back is an optional param | |
if (!callback) { // if callback omitted, we return a promise | |
const performWork = async () => obj // this simulates work being done before resolving | |
return new Promise(async (resolve, reject) => { // return an async promise wrapper | |
const value = await performWork() // do the work | |
resolve(value) // resolve the promise | |
}) | |
} | |
const cb = obj // if callback present, we return it | |
callback(cb) | |
} | |
const test = { test: 1337 } // this is the sample data that comes in as obj | |
// Promise version | |
myFunc(test).then((res) => console.log('Promise version', res)) // demonstration as promise | |
// Callback version | |
myFunc(test, (res) => { // demonstration as callback | |
console.log('Callback version', res) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment