Skip to content

Instantly share code, notes, and snippets.

@shinzui
Forked from mjackson/resolvePromise.js
Created September 24, 2016 18:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shinzui/169c9691bc36b4adf089ef6c79033d9e to your computer and use it in GitHub Desktop.
Save shinzui/169c9691bc36b4adf089ef6c79033d9e to your computer and use it in GitHub Desktop.
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