Skip to content

Instantly share code, notes, and snippets.

@Magellol
Created February 27, 2017 18:35
Show Gist options
  • Save Magellol/bb8532e58c3940b8f7ba135e36071efc to your computer and use it in GitHub Desktop.
Save Magellol/bb8532e58c3940b8f7ba135e36071efc to your computer and use it in GitHub Desktop.
Promisify error-first callback based functions.
function promisify(fn) {
return (...args) => {
return new Promise((resolve, reject) => {
fn(...args, (error, result) => {
if (error) {
return reject(error);
}
return resolve(result);
});
});
}
}
// Examples
const fs = require('fs');
const readFile = promisify(fs.readFile);
readFile('test.txt')
.then(console.log)
.catch(console.error);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment