How does Asynchronous programming work in a single threaded programming model?

Say it with me now: async programming does not necessarily mean multi-threaded.

Javascript is a single-threaded runtime – you simply aren’t able to create new threads in JS because the language/runtime doesn’t support it.

Frank says it correctly (although obtusely) In English: there’s a main event loop that handles when things come into your app. So, “handle this HTTP request” will get added to the event queue, then handled by the event loop when appropriate.

When you call an async operation (a mysql db query, for example), node.js sends “hey, execute this query” to mysql. Since this query will take some time (milliseconds), node.js performs the query using the MySQL async library – getting back to the event loop and doing something else there while waiting for mysql to get back to us. Like handling that HTTP request.

Edit: By contrast, node.js could simply wait around (doing nothing) for mysql to get back to it. This is called a synchronous call. Imagine a restaurant, where your waiter submits your order to the cook, then sits down and twiddles his/her thumbs while the chef cooks. In a restaurant, like in a node.js program, such behavior is foolish – you have other customers who are hungry and need to be served. Thus you want to be as asynchronous as possible to make sure one waiter (or node.js process) is serving as many people as they can.

Edit done

Node.js communicates with mysql using C libraries, so technically those C libraries could spawn off threads, but inside Javascript you can’t do anything with threads.

Leave a Comment