Skip to content

Instantly share code, notes, and snippets.

@offero
Created November 24, 2016 17:20
Show Gist options
  • Save offero/1ba0ef314754cf1728037e57f6a1656b to your computer and use it in GitHub Desktop.
Save offero/1ba0ef314754cf1728037e57f6a1656b to your computer and use it in GitHub Desktop.
Wrap a callback and return a promise
function doThingThatReturnsPromise(arg1) {
return new Promise(function(resolve, reject) {
fnThatDoesTheThingButAcceptsACallback(arg1, function callback(err, result) {
if(err) {
// the callback was called with an error
return reject(err);
}
// the callback was called with a result
resolve(result);
});
});
}
// cool es6 function version
function doThingThatReturnsPromiseES6(arg1) {
return new Promise((resolve, reject) => {
fnThatDoesTheThingButAcceptsACallback(arg1, (err, result) => {
err && reject(err) || resolve(result);
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment