Skip to content

Instantly share code, notes, and snippets.

@lac5
Created September 19, 2019 15:06
Show Gist options
  • Save lac5/aab350a6d7f9568c5709beeed970d50d to your computer and use it in GitHub Desktop.
Save lac5/aab350a6d7f9568c5709beeed970d50d to your computer and use it in GitHub Desktop.
/**
* 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