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)

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more