Blocking:
Blocking code means that the execution of code stops at a particular point until the operation is completed. During this time, no other code can be executed. It's like standing in line at the bank until your turn is over.
Imagine you're at a busy restaurant with only one chef. You order a dish, and the chef starts cooking it. No other orders can be cooked until your dish is finished. That's like blocking code: everything stops until the current task is done.
Non-Blocking:
Non-blocking code allows other operations to be executed while waiting for the completion of the current operation. Think of it as placing your order at a drive-through and then moving forward to pick it up while someone else places their order.
Now, imagine the restaurant has multiple chefs. You place your order, and while one chef starts cooking your dish, other chefs can cook other orders at the same time. This means that everyone gets their food faster. That's like non-blocking code: multiple tasks can be handled simultaneously, making things more efficient.
Example:
Blocking:
const fs = require('fs');
let data = fs.readFileSync('file.txt');
console.log(data);
Non-Blocking:
const fs = require('fs');
fs.readFile('file.txt', (err, data) => {
if (err) throw err;
console.log(data);
});
console.log('This runs immediately, even before the file is read');
In the non-blocking example, fs.readFile doesn't stop the execution of the code. Instead, it runs the callback function once the file has been read, allowing other code to run in the meantime.
Why It Matters:
Blocking Code can make your application sluggish, as it waits for each operation to complete before moving on.
Non-Blocking Code helps in building responsive, efficient applications by handling multiple tasks simultaneously.
Top comments (0)