Why is a function and a callback non-blocking in Node.JS?

后端 未结 4 1772
你的背包
你的背包 2020-12-06 01:37

The novice understanding of Node is that if I re-write synchronous, or in-line code, to utilize functions / callbacks, I can ensure that my code is non-blocking. I\'m curio

4条回答
  •  温柔的废话
    2020-12-06 02:34

    The accepted answer is great, but I would like to add something purely related to nonblocking, specifically this part of the question:

    Or is it because I/O events are just fundamentally blocking operations meaning that they seize control and don't give it back until done...

    Asynchronous IO is possible even without a framework providing its own pool of IO worker threads. Indeed, it can be done without any multi-threading at all as long as the underlying (operating) system provides some mechanism to do non-blocking IO.

    Typically this boils down to a system call like POSIX's select (or Microsoft's version of the same), or more recent variations on the same idea like Linux's epoll.

    Hypothetically speaking, if we see a function like db.query in your example, and assuming we also know that the framework providing that function does not rely on any multi-threading, then it is usually safe to conclude that:

    • The framework keeps track of a global list of IO descriptors and callbacks associated with any non-blocking IO requests which were initiated, like your db.query call.
    • The framework has or relies on some sort of main application event loop. This could be anything from an old-school while(true) to something like libev
    • Somewhere in said main loop, select or a similar function will be used to check if any of those pending IO requests have finished yet.
    • When a finished IO request is found, its associated callback gets called, after which the main loop resumes.

    An SQL DB call like your db.query probably uses network socket IO and not file IO, but from your perspective as an application developer, socket and file descriptors are handled in nearly identical ways on many operating systems, and can both be passed to select on POSIX-likes anyway.

    This is usually how single-threaded, single-process server applications "juggle" multiple simultaneous connections.

提交回复
热议问题