Skip to content

Instantly share code, notes, and snippets.

@jtenner
Created June 27, 2017 13:56
Show Gist options
  • Save jtenner/79eaf4d7fe61fb542461024e7765050f to your computer and use it in GitHub Desktop.
Save jtenner/79eaf4d7fe61fb542461024e7765050f to your computer and use it in GitHub Desktop.
//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