Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.