Skip to content

Instantly share code, notes, and snippets.

@jaidetree
Created October 25, 2016 18:17
Show Gist options
  • Select an option

  • Save jaidetree/0a290c416aec3585e03929199ef40d4b to your computer and use it in GitHub Desktop.

Select an option

Save jaidetree/0a290c416aec3585e03929199ef40d4b to your computer and use it in GitHub Desktop.
Best attempt at a general wrapper around many types of callbacks.
/**
* Wraps the given callback in a promise
* @param {function} callback - Callback to call & wrap in a promise
* @param {...*} args - Arguments to send to the callback. Send the promise
* method to prefil arguments.
* @returns {promise} A promise resolved when callback is fired
* @example
* return promise(this.setState, data);
* return promise(setTimeout, promise, 500);
*/
export default function promise (callback, ...args) {
return new Promise((resolve, reject) => {
let index = args.indexOf(promise);
function handler (...results) {
let err = results[0];
if (err && err instanceof Error) reject(err);
else resolve(results);
}
/** Add the handler at the given promise arg or at the end */
args.splice(index > -1 ? index : args.length, 1, handler);
callback(...args);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment