Created
September 19, 2019 15:06
-
-
Save lac5/aab350a6d7f9568c5709beeed970d50d to your computer and use it in GitHub Desktop.
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
/** | |
* Turns standard callback functions into promises. | |
* Useful for async functions. | |
* | |
* Example: | |
* (async ()=> { | |
* var file = await p(f => fs.readFile('file.txt', f)); | |
* file += 'modified'; | |
* console.log(file); | |
* await p(f => fs.writeFile, 'file-modified.txt', f)); | |
* })().catch(console.error); | |
* | |
* @param {Function} f Used to insert the callback function used by the promise. | |
* @return {Promise} Returns data or error from callback. | |
*/ | |
export function p(f) { | |
return new Promise((resolve, reject) => { | |
f((error, data) => error ? reject(error) : resolve(data)); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment