Why in Node.js you need to do asynchronous operations
You may have wondered why so many functions in Node.js take a callback. Instead of returning results as the function return value, the “results” are delivered by calling the callback function at a later time. You are trying to wrap your head around why so many operations in Node.js are asynchronous.
It may seem counterintuitive at first, but there is a reason for having to do a lot of asynchronous operations.
In a server application you have to do small and quick code blocks and then get out of the way for other requests to get their turn. The other requests obey to this same contract, and collaboratively they make single thread serve multiple requests.
Callbacks allow making use of waiting time
Asynchronous operations setup the call and then return immediately without any results. The results are delivered at a later time by calling the provided callback. During the time between initiating the call and getting the results, other computations can take place. This allows the waiting time to be used to serve other requests.
Asynchronous operations allow one thread to serve multiple requests
- Let asynchronous I/O happen by returning control back to the event loop
- Blocking and Non-Blocking in Node.js
There are 350 000 NPM packages. Your task: pick one.
Learn what to look for in a reliable NPM package.