Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
An easy way to do async APIs in JavaScript that support both promises *and* callbacks!
// 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