Last active
September 9, 2018 08:23
-
-
Save mjackson/bc0f2e1edf0862a2619ac38a721f9005 to your computer and use it in GitHub Desktop.
An easy way to do async APIs in JavaScript that support both promises *and* callbacks!
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
// Here is a function that I use all the time when creating public | |
// async APIs in JavaScript: | |
const resolvePromise = (promise, callback) => { | |
if (callback) | |
promise.then(value => callback(null, value), callback) | |
return promise | |
} | |
// Sometimes I like to use callbacks, but other times a promise is | |
// easier to use. And sometimes it's hard to know up front which style | |
// you'll need later on. resolvePromise is an easy way to support both. | |
// Here, we wrap doSomethingAsync (could be any promise-only API, e.g. | |
// window.fetch) to give consumers the flexibility to use a trailing | |
// callback arg if they prefer callbacks to promises. | |
const somethingAsync = (a, b, c, callback) => | |
resolvePromise( | |
doSomethingAsync(a, b, c), // Can be any promise-only API | |
callback | |
) | |
// Now, you can use either style: | |
somethingAsync(a, b, c).then(value => { | |
// Promises work! | |
}, error => { | |
// Use a separate function for handling errors. | |
}) | |
somethingAsync(a, b, c, (error, value) => { | |
// Callbacks too! Use one function to handle both success and error. | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment