- Web Development with MongoDB and Node(Third Edition)
- Bruno Joseph D'mello Mithun Satheesh Jason Krol
- 233字
- 2021-07-08 10:32:36
Non-blocking asynchronous execution
One of the most powerful features of Node.js is that it is both event-driven and asynchronous. So, how does an asynchronous model work? Imagine you have a block of code and at some nth line you have an operation that is time consuming. What happens to the lines that follow the nth line while this code gets executed? In normal synchronous programming models, the lines that follow the nth line will have to wait until the operation at that line completes. An asynchronous model handles this case differently.
Let us visualize this scenario with the help of the following code and diagram:

In the preceding case, the setTimeout() method is provided by JavaScript (Node.js) API. Hence, this method is recognized as synchronous and is executed in a different execution context. According to functionality to setTimeout() , it executes the callback function after a specified duration, in our case after three seconds.
Further, the current execution is never blocked for a process to complete. When Node.js API determines that the completion of an event has been fired, it will execute your callback function at that moment.
In a typical synchronous programming language, executing the preceding code will yield the following output:

- Google Flutter Mobile Development Quick Start Guide
- Android 7編程入門經典:使用Android Studio 2(第4版)
- 重學Java設計模式
- HTML5入門經典
- 算法訓練營:提高篇(全彩版)
- Android開發案例教程與項目實戰(在線實驗+在線自測)
- 青少年信息學競賽
- ServiceNow:Building Powerful Workflows
- Spring Boot+Vue全棧開發實戰
- Clean Code in C#
- Nagios Core Administration Cookbook(Second Edition)
- Machine Learning for OpenCV
- 軟件測試分析與實踐
- Deep Learning for Natural Language Processing
- 基于JavaScript的WebGIS開發