Skip to content

Instantly share code, notes, and snippets.

@joshwcomeau
Created May 10, 2016 11:03
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 joshwcomeau/48e6a56c8a7356aa86ae7449d3eabdb8 to your computer and use it in GitHub Desktop.
Save joshwcomeau/48e6a56c8a7356aa86ae7449d3eabdb8 to your computer and use it in GitHub Desktop.
convert-to-async
// If the function does not take an 'errback' callback, we can still wrap our
// functions. Let's use a fictional method:
fictionalMethod(data, successCallback, failureCallback) {
fictionalAsyncOperation(data, result => {
if ( !result ) {
return failureCallback(new Error('Result not found'))
} else {
return successCallback(result);
}
})
}
// We would use this method, traditionally, like so:
fictionalMethod({ foo: 'bar' }, (result) => {
res.json(result);
}, (err) => {
throw err;
});
// Here's what our promise wrapper looks like.
// The outer wrapping and rest/spreading is unchanged.
// We simply need to modify the inner callback to resolve/reject
// based on the signature of the wrapped function.
function wrapWithPromise(wrappedFunction, ...args) {
return new Promise((resolve, reject) => {
wrappedFunction(...args, (result) => {
return resolve(result);
}, (err) => {
return reject(err);
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment