Last active
December 13, 2017 13:46
-
-
Save mheap/4abf07d84a7ae08b729d5934d43a4e66 to your computer and use it in GitHub Desktop.
promise-and-callback-support
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
const promiseOrCallback = (promise, callback) => { | |
if (typeof callback != "function") { | |
return promise; | |
} | |
return promise | |
.then((result) => (callback(null, result))) | |
.catch(callback); | |
}; | |
const foo = (a, b, callback) => { | |
const promise = new Promise((resolve, reject) => { | |
return resolve(a + b); | |
}); | |
return promiseOrCallback(promise, callback); | |
} |
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
const promiseOrCallback = function(func, callback) { | |
return new Promise(async (resolve, reject) => { | |
try { | |
const data = await func(); | |
if (typeof callback == "function") { | |
return callback(null, data); | |
} | |
return resolve(data); | |
} catch (err) { | |
if (typeof callback == "function") { | |
return callback(err, null); | |
} | |
return reject(err); | |
} | |
}); | |
}; | |
const foo = (a, b, callback) => { | |
return promiseOrCallback(function() { | |
return new Promise((resolve, reject){ | |
return resolve(a + b); | |
}); | |
}, callback); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment