DEV Community

PUSHAN VERMA
PUSHAN VERMA

Posted on

2

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

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

đź‘‹ Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay