Created
May 10, 2016 11:03
-
-
Save joshwcomeau/48e6a56c8a7356aa86ae7449d3eabdb8 to your computer and use it in GitHub Desktop.
convert-to-async
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
// 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