In an HTTPS POST request, Node.js initiates the request via libuv, which delegates the actual network I/O to the OS. The OS performs the real work like sending and receiving data. When data is ready, it notifies libuv, which queues the callback. The event loop then executes these callbacks in the poll phase, including response handling and streaming data events.
Note: Async/await does not make Node.js asynchronous. Node.js is already asynchronous and non-blocking by design.
What async/await does:
- Makes async code easier to read
- Makes error handling cleaner
- Improves maintainability
[Node.js] → Initiates request
↓
[libuv] → Registers & delegates
↓
[OS] → Performs actual network I/O (real worker)
↓
[OS signals readiness]
↓
[libuv] → Queues callback
↓
[Event Loop - Poll phase] → Executes callback
| Component | Role |
|---|---|
| Node.js | Initiates request |
| libuv | Registers + listens (Thread pool not used) |
| OS | Performs actual network work |
| Poll phase | Executes callbacks |
| Thread pool | Not used here |
Example1
const https = require("https");
const data = JSON.stringify({ name: "Ghanshyam" });
const options = {
hostname: "api.example.com",
path: "/users",
method: "POST",
headers: {
"Content-Type": "application/json",
"Content-Length": data.length
}
};
const req = https.request(options, (res) => {
console.log("STATUS:", res.statusCode);
res.on("data", (chunk) => {
console.log("BODY:", chunk.toString());
});
res.on("end", () => {
console.log("Response ended");
});
});
req.on("error", (err) => {
console.error("Error:", err);
});
req.write(data);
req.end();
Example2 (with Promise)
function fetchData(url) {
return new Promise((resolve, reject) => {
https.get(url, (res) => {
if (res.statusCode !== 200) {
reject(new Error(`Status Code: ${res.statusCode}`));
res.resume(); // consume response to free memory
return;
}
let data = "";
res.on("data", chunk => data += chunk);
res.on("end", () => resolve(data));
}).on("error", reject);
});
}
Example4 (without async await)
fetchUser()
.then(user => fetchOrders(user.id))
.then(orders => fetchPayment(orders))
.then(payment => console.log(payment))
.catch(err => console.error(err));
Example4 (with async await)
async function process() {
try {
const user = await fetchUser();
const orders = await fetchOrders(user.id);
const payment = await fetchPayment(orders);
console.log(payment);
} catch (err) {
console.error(err);
}
}
No comments:
Post a Comment