Skip to content

Instantly share code, notes, and snippets.

@Paratron
Created December 12, 2018 13:20
Show Gist options
  • Save Paratron/e1c952bd79abc15d222076ebee8fa8d1 to your computer and use it in GitHub Desktop.
Save Paratron/e1c952bd79abc15d222076ebee8fa8d1 to your computer and use it in GitHub Desktop.
Simple async functionality for native style nodeJS functions
// The normal async programming flow in nodeJS can get hairy, quickly:
function readAndParse(filename, callback){
fs.readFile(filename, 'utf8', (err, data) => {
if(err){
callback(err, null);
return;
}
myParser.doParsing(data, (err, result) => {
if(err){
callback(err, null);
return;
}
callback(null, result);
});
});
}
// With a small helper function, this nested callback construction can be flattened to this:
async function readAndParse(filename){
const src = await asPromise(fs.readFile, filename, 'utf8');
const result = await asPromise(myParser.doParsing, src);
return result;
}
// This is the wrapper function `asPromise`, that can take any nodeJS callback style function and wrap it into a promise:
/**
* Converts a nodeJS native style function and calls it as a promise.
* @param {function} normalFunc The original nodeJS function to wrap in a promise.
* @param {any...} normalArguments Any arguments you want to pass to the wrapped function.
* @returns {Promise<any>}
*/
const asPromise = (normalFunc, ...normalArguments) => new Promise((resolve, reject) => {
const combinedArguments = [...normalArguments, function () {
const [err, ...rest] = arguments;
if (err) {
reject(err);
}
resolve.apply(normalFunc, rest);
}];
normalFunc.apply(normalFunc, combinedArguments);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment