Created
February 23, 2019 01:26
-
-
Save wesalvaro/d945d47f0e0650cd514ae13ad6de1407 to your computer and use it in GitHub Desktop.
Simple function to convert functions with callback APIs to have Promise APIs.
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
/** | |
* Converts a function from a callback API to a Promise API. | |
* | |
* Example: | |
* const context = navigator.geolocation; | |
* const f = context.getCurrentPosition; | |
* const getCurrentPosition = promisify(f, 0, 1, context); | |
* const enableHighAccuracy = true; | |
* getCurrentPosition({enableHighAccuracy}) | |
* .then(r => console.log(r.coords), e => console.error(e)); | |
* | |
* @param {!Function} f a function | |
* @param {number} successI parameter index of the success callback | |
* @param {number=} errorI parameter index of the error callback | |
* @param {?=} context context to use when calling f | |
*/ | |
const promisify = (f, successI, errorI, context) => { | |
return function() { | |
const args = [].slice.call(arguments, 0); | |
return new Promise((resolve, reject) => { | |
args.splice(successI, 0, resolve); | |
if (errorI != null) { | |
args.splice(errorI, 0, reject); | |
} | |
f.apply(context || this, args); | |
}); | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment