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
转载本站任何文章请注明：转载至神刀安全网，谢谢神刀安全网 » Why in Node.js you need to do asynchronous operations