Last active
August 6, 2017 13:53
-
-
Save roc/b70f0b66090a636dca244355f93d536d to your computer and use it in GitHub Desktop.
wrap a callback bound function in a promise
This file contains 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
// mercilessly culled from npm-promisify | |
const alreadyAPromise = o => o && typeof o.then === "function" && typeof o.catch === "function"; | |
// As simple as I can get it: | |
// wrap a function, apply a callback | |
// return the callback response in Promise.resolve | |
// | |
// NB. This doesn't handle node style err first | |
// callbacks with a rejection, but you could... | |
const press = (original, target) => { | |
return (...args) => { | |
// todo handle rejection? (😭) | |
return new Promise(resolve => { | |
// Apply a callback in which we just return | |
// whatever is in the response in a resolve() | |
args.push(function callback(...values) { | |
// todo handle multiple values response | |
// as array or not? | |
resolve(values[0]) | |
}); | |
// Call the function | |
const response = original.apply(target, args); | |
// If it looks like original already returns a promise, | |
// then just resolve with that promise. | |
if (alreadyAPromise(response)) { | |
resolve(response); | |
} | |
}); | |
}; | |
}; | |
// usage... | |
// press(chrome.windows.getCurrent)().then(resp => { | |
// console.log(resp); | |
// }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment