Created
February 27, 2017 18:35
-
-
Save Magellol/bb8532e58c3940b8f7ba135e36071efc to your computer and use it in GitHub Desktop.
Promisify error-first callback based functions.
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
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