Skip to content

Instantly share code, notes, and snippets.

@roc
Last active August 6, 2017 13:53
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 roc/b70f0b66090a636dca244355f93d536d to your computer and use it in GitHub Desktop.
Save roc/b70f0b66090a636dca244355f93d536d to your computer and use it in GitHub Desktop.
wrap a callback bound function in a promise
// 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