Created
June 27, 2017 13:56
-
-
Save jtenner/79eaf4d7fe61fb542461024e7765050f 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
//promisify.js | |
module.exports = (func, bound = null) => (...args) => new Promise( | |
(resolve, reject) => func.call(bound, ...args, (err, ...results) => err ? reject(err) : resolve(...results)) | |
); | |
/**************************************************************************************** | |
* This function is used to turn a callback style function into an await(able) result. | |
* | |
* For example, fs.readFile takes two parameters: fs.readFile(name, callback); | |
* | |
* Callback needs to look like this: function(error, result) | |
****************************************************************************************/ | |
fs.readFile(name, function(error, result) { | |
if (err) | |
return console.log(error); | |
console.log(result); | |
}); | |
// What if instead we wrapped the fs.readFile function with promisify and used the await keyword in an async function? | |
(async function() { | |
'use strict'; | |
let readFile = promisify(fs.readFile); | |
let result = await readFile(name); | |
console.log(result); | |
}()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment