Skip to content

Instantly share code, notes, and snippets.

@SarasArya
Last active April 2, 2017 06:39
Show Gist options
  • Save SarasArya/ad9556f87cfb345caf929fb87cb4b1d5 to your computer and use it in GitHub Desktop.
Save SarasArya/ad9556f87cfb345caf929fb87cb4b1d5 to your computer and use it in GitHub Desktop.
This gist is for people who are new to JS, and want to write libraries which support both callbacks and Promises architecture.
// This file provides an example of how you can expose both Promises and callback support to your functions
const fs = require('fs');
//This function can be called via callbacks, as well as Promises
const readFileAsArray = function(file, cb = () => {}) { //callback is made an empty function in case I am using Promises,
// in which case I wont be passing this argument and it wouldn't throw and undefined variable error.
return new Promise((resolve, reject) => { //create a new promise
fs.readFile(file, (err, data) => {
if (err) {
reject(err); //To support promises
cb(err); //To support callback
} else {
const lines = data.toString().trim().split("\n");
resolve(lines); //Resolve for promise
cb(null, lines); //Err argument null for success
}
});
});
};
/*Callback Style*/
readFileAsArray('./numbers.txt', (err, lines) => { //Please create this numbers.txt file for the above program to run.
if (err) {
throw err;
} else {
const numbers = lines.map(Number);
const oddNumberCount = numbers.filter((item) => {
return item % 2 === 1;
});
console.log(`Odd Number callback count = ${oddNumberCount.length}`);
}
});
/*Promise style*/
readFileAsArray('./numbers.txt') //Please create this numbers.txt file for the above program to run.
.then(lines => {
const numbers = lines.map(Number);
const oddNumberCount = numbers.filter((item) => {
return item % 2 === 1;
});
console.log(`Odd Number promise count = ${oddNumberCount.length}`);
})
.catch(err => {
console.log(err);
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment