0% found this document useful (0 votes)
3 views1 page

Node.js Async Programming with Callbacks

Uploaded by

Solaim Faisal
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views1 page

Node.js Async Programming with Callbacks

Uploaded by

Solaim Faisal
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Asynchronous Programming in Node.

js with
Callbacks

In this workshop example, we will learn how [Link] handles asynchronous programming using
callbacks. JavaScript is single-threaded, but [Link] uses an event loop to handle non-blocking
tasks like timers, file system operations, and network requests.

// Import the 'fs' module to work with files


const fs = require("fs");

// Step 1: Print something immediately


[Link]("Step 1: Program started");

// Step 2: Set a timer (asynchronous)


setTimeout(() => {
[Link]("Step 2: Timer finished after 2 seconds");
}, 2000);

// Step 3: Read a file asynchronously


[Link]("[Link]", "utf8", (err, data) => {
if (err) {
[Link]("Step 3: Error reading file", err);
} else {
[Link]("Step 3: File content is -> " + data);
}
});

// Step 4: Another asynchronous task with setTimeout


setTimeout(() => {
[Link]("Step 4: Another timer finished after 1 second");
}, 1000);

// Step 5: This will run immediately (synchronous)


[Link]("Step 5: Program ended (but async tasks are still running!)");

Explanation of Steps:
1. Step 1 runs immediately because [Link] is synchronous. 2. Step 2 uses setTimeout, which
is asynchronous. [Link] registers the task and moves on. 3. Step 3 uses [Link], which is
asynchronous. [Link] will execute the callback once file reading is complete. 4. Step 4 is another
timer, scheduled for 1 second. Even though it comes later in code, it may finish before Step 2. 5.
Step 5 runs instantly because it is synchronous. ■ Actual output order: Step 1: Program started
Step 5: Program ended (but async tasks are still running!) Step 4: Another timer finished after 1
second Step 2: Timer finished after 2 seconds Step 3: File content is -> (whatever is inside
[Link])

Key Workshop Takeaways:


- JavaScript is single-threaded, but [Link] handles async tasks using the Event Loop. -
Synchronous code runs first, async code waits until it’s ready. - Callbacks are used to tell [Link]
what to do when the async task is complete. - Real-world async tasks include file system
operations, network requests, database queries, and timers.

You might also like