Node.js: Code Outside the Browser / Async Programming in Node.js

What is Asynchronous Programming?

πŸ”΄ The problem:

In regular (synchronous) code, each task runs one after the other. If one task takes time (like reading a file), everything else has to wait, slowing your program.

🟒 The async solution:

Asynchronous programming lets some tasks run in the background, so your app can continue doing other things in the meantime.

Think of it like:

πŸ§‹ You order a bubble tea β†’ the cafΓ© takes time to make it β†’ but you don’t stand there doing nothing β€” you scroll Insta while they prep it.

That’s asynchronous behavior. Your app doesn’t "freeze" while waiting.


βœ… In Node.js:

Node.js is built to run asynchronously, which makes it perfect for handling lots of tasks β€” like reading files, fetching data, or handling user requests β€” without blocking the rest of the app.

Synchronous code example:

//index.js
console.log("Start execution...");
console.log("Login execution...");
console.log("Complete execution...");

Asynchronous code example:

In the given below example, the setTimeout() function is used to simulate a time-consuming asynchronous task (e.g., a complex operation that takes 2 seconds).

//index.js
console.log("Start execution...");

setTimeout(() => {
    console.log("Login execution...");
}, 2000); // 2 second delay

console.log("Complete execution...");

Here's what happens:

  • The program starts by executing console.log("start exe...") immediately.

  • Then it encounters setTimeout(), which schedules the callback (containing console.log("login exe...")) to be executed after 2 seconds, but does not block the thread.

  • The next line, console.log("complete exe..."), is executed right away, without waiting for the timeout.

  • Finally, after the 2-second delay, the callback inside setTimeout() is executed, printing "login exe...".