What is Callback Queue in Node.js: Explanation and Example
callback queue is where callback functions wait after asynchronous operations complete, before the event loop executes them. It ensures callbacks run only when the main code and current tasks finish, keeping Node.js non-blocking and efficient.How It Works
Imagine you are at a restaurant. You place your order and then wait while the chef prepares your food. Instead of standing at the counter, you sit at your table until your meal is ready. In Node.js, the callback queue is like that waiting area where your order (callback) waits after the kitchen (asynchronous operation) finishes cooking.
When Node.js finishes running the current code, it checks the callback queue. If there are callbacks waiting, it takes them one by one and runs them. This process is managed by the event loop, which keeps Node.js fast and responsive by not blocking the main thread.
Example
This example shows how a callback is added to the callback queue after a delay, then executed by the event loop.
console.log('Start'); setTimeout(() => { console.log('Callback from callback queue'); }, 1000); console.log('End');
When to Use
Use the callback queue when you want to run code after an asynchronous task finishes, like reading a file, making a network request, or waiting for a timer. It helps keep your app responsive by not blocking other tasks while waiting.
For example, in a web server, callbacks in the queue handle incoming requests without stopping the server from accepting new ones. This makes Node.js great for real-time apps and APIs.
Key Points
- The callback queue holds callbacks ready to run after async tasks complete.
- The event loop moves callbacks from the queue to the main thread for execution.
- This system keeps Node.js non-blocking and efficient.
- Callbacks in the queue run only after the current code finishes.