DEV Community

PUSHAN VERMA
PUSHAN VERMA

Posted on

Reading Files Serially through Callbacks and Promises

Through Callbacks

const fs =require('fs');

console.log('Before');

fs.readFile('f1.txt',cb1);

function cb1(err,data){
if(err)
{
console.log(error);
}
else
{
console.log(" "+data);
fs.readFile('f2.txt',cb2);
}
}

function cb2(err,data){
if(err)
{
console.log(err);
}
else
{
console.log(" "+data);
fs.readFile('f3.txt',cb3);
}
}

function cb3(err,data){
if(err)
{
console.log(err);

}
else
{
    console.log(" "+data);
}
Enter fullscreen mode Exit fullscreen mode

}

console.log('After');

//👉 ans ->
// Before
// After
// this is file 1
// this is file 2
// this is file 3

Through Promise

const fs =require('fs');

console.log('Before');

let f1p=fs.promises.readFile('f1.txt');

f1p.then(cb1);

function cb1(data){
console.log("File data->"+data);
let f2p=fs.promises.readFile('f2.txt');
f2p.then(cb2);
}

function cb2(data)
{
console.log("File data->"+data);
let f3p=fs.promises.readFile('f3.txt');
f3p.then(cb3);
}

function cb3(data){
console.log("File data->"+data);

}

console.log('After');

//👉 ans ->
// Before
// After
// File data->this is file 1
// File data->this is file 2
// File data->this is file 3

📌Handwritten Notes:
https://github.com/pushanverma/notes/blob/main/webd/Serially%20in%20Js%20.pdf

Top comments (0)