Created
October 25, 2016 18:17
-
-
Save jaidetree/0a290c416aec3585e03929199ef40d4b to your computer and use it in GitHub Desktop.
Best attempt at a general wrapper around many types of callbacks.
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
| /** | |
| * 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