Last active
July 17, 2017 19:13
-
-
Save pareddy113/97a5194842cb378e2b2fd68c1751f10c to your computer and use it in GitHub Desktop.
node js callbacks - multiple callbacks - multiple versions
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
//different version of same multiple callback function | |
//a b c in the order | |
//version 1 (not elegant way) | |
var fs = require('fs'); | |
function asyncRead(callback){ | |
fs.readFile('sample.txt','utf8',function(err, data){ | |
if (err) raise ("no output file"); | |
var numberOfNewLines = data.split("\n"); | |
callback(numberOfNewLines); | |
fs.readFile('sample1.txt','utf8',function(err, data){ | |
if (err) raise ("no output file"); | |
var numberOfNewLines = data.split("\n"); | |
callback(numberOfNewLines); | |
fs.readFile('sample2.txt','utf8',function(err, data){ | |
if (err) raise ("no output file"); | |
var numberOfNewLines = data.split("\n"); | |
callback(numberOfNewLines); | |
}); | |
}); | |
}); | |
} | |
asyncRead(function(array){console.log(array)}); | |
//version 2 | |
var fs = require('fs'); | |
function asyncRead(callback){ | |
fs.readFile('sample.txt','utf8',cb); | |
} | |
function cb(err, data){ | |
if (err) raise ("no output file"); | |
var numberOfNewLines = data.split("\n"); | |
console.log(numberOfNewLines); | |
fs.readFile('sample1.txt','utf8', cb1); | |
} | |
function cb1(err, data){ | |
if (err) raise ("no output file"); | |
var numberOfNewLines = data.split("\n"); | |
console.log(numberOfNewLines); | |
fs.readFile('sample2.txt','utf8', cb2); | |
} | |
function cb2(err, data){ | |
if (err) raise ("no output file"); | |
var numberOfNewLines = data.split("\n"); | |
console.log(numberOfNewLines); | |
}; | |
asyncRead(function(array){console.log(array)}); | |
//version 3 (preferred way) | |
var fs = require('fs'); | |
function asyncRead(callback){ | |
fs.readFile('sample.txt','utf8',function(err, data){ | |
if (err) raise ("no output file"); | |
var numberOfNewLines = data.split("\n"); | |
callback(numberOfNewLines); | |
helper(callback); | |
}); | |
} | |
asyncRead(function(array){console.log(array)}); | |
function helper(callback){ | |
fs.readFile('sample1.txt','utf8',function(err, data){ | |
if (err) raise ("no output file"); | |
var numberOfNewLines = data.split("\n"); | |
callback(numberOfNewLines); | |
helper1(callback); | |
}); | |
} | |
function helper1(callback){ | |
fs.readFile('sample2.txt','utf8',function(err, data){ | |
if (err) raise ("no output file"); | |
var numberOfNewLines = data.split("\n"); | |
callback(numberOfNewLines); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment