Reactor mode of node.js and asynchronous programming

Jiedao jdon 2021-05-04 09:28:13
reactor mode node.js node js

stay Ruby on Rails and NodeJS There was a religious war of words between developers : Sequential programming style Vs Programming based on events . At present, most of them Web Applications include Ruby on Rails, Java Spring, Django It's all sequential programming style . Sequential programming is very simple and readable , Most developers think in a sequential way , Like to divide an application logic into sequential sequential steps . Sequential programming usually leads to clogging I/O, Because threads follow a first come, first served multitasking approach , Rather than a collaborative, multitasking approach , Not the blockage I/O Can lead to better scalability and performance .

This is an article about Node.js Non clogging reactive Programming cases , The article is based on a simple basis id Of the query RESTful Take the case as an example , From blockage IO When it comes to the use of callback functions , Then talk about how to strike a balance between code scalability and readability , introduce Promise And Fibers Programming . The main idea of translation is as follows :

The following code is based on facebook Of id Query user event data implementation , The style of sequential programming code is as follows (JS Pseudo code ):

function getUserEvents(request,response){
var facebook_id = request.param('facebook_id');
var user = db.users.findOne({fb_id:facebook_id});
var events ={});

Sequential programming usually leads to clogging I/O, Because threads follow a first come, first served multitasking approach , Rather than a collaborative, multitasking approach .

Now let's gradually introduce asynchrony to improve this code .

Callback based solutions

In order to solve the jam I/O problem , The code can be divided into three parts :

1. On the Internet or IO Procedure handling before calling .

2. Network or IO call .

3. From the Internet or IO Call to get the return data processing .

The above three steps are performed separately , Then they are in NodeJS Is triggered in the event loop of .

function getUserEvents(request,response){
var returnEvents = function(err,events){
if (err) respone.status(500).send(err);;
var givenUserFindAndReturnEvents = function(err,user){
if (err) respone.status(500).send(err);;{},returnEvents);
var findUserAndReturnEvents = function(){
var facebook_id = request.param('facebook_id');
db.users.findOne({fb_id:facebook_id}, givenUserFindAndReturnEvents);

Notice that the request and response are not passed into the subfunction , But subfunctions can access request and response, Because the subfunction is a javascript Closure . ( When calling findUserAndReturnEvents Function time , amount to findUserAndReturnEvents -> givenUserFindAndReturnEvents ->returnEvents Such a streaming call )

These three sub functions are executed asynchronously , givenUserFindAndReturnEvents and returnEvents Is in findUserAndReturnEvents Trigger execution in the callback function .

These three sub functions can be executed using nested lambda Function style or findUserAndReturnEvents. givenUserFindAndReturnEvents.returnEvents such in-line The way .

This code has several characteristics :

1. The code is divided into two stages before and after network call

2. In order to complete the sub function task, the sub function caller must pass a callback function .

3. Sequential logic is expressed as asynchronous

4. Asynchronous code is more scalable , But maybe increase the response latency .

5. But callbacks cause readability problems : Back to hell callback hell.

6. Tracking the execution process is difficult , So it's called spaghetti code spaghetti-code.

7. unchecked API Restrictions may prevent you from organizing your code , It's invasive .

8. Functions are hierarchical .

be based on Promise Solutions for

In order to solve the problem of callback to hell , We use code structure libraries like q promise. Promise Libraries provide some standard code style and structure , Make the code easier to read .

var loadEventsForUser = function(err,user){
var findUser = function(){
var facebook_id = request.param('facebook_id');
return db.users.findOne({fb_id:facebook_id});
function getUserEvents(request,response){
var success = function(events){
var error = function(err){

The key is how to write the last line .

The code has been divided into small independent functions , They're chained together , It uses .then and .fail function . Another important feature is processing exception, The above code can detect errors and call the corresponding callback function , Error handling is isolated .

Important features :

1. Functions are flat , such as findUser Can be independent of loadEventsForUser Function call .

2. It's not always easy to slice sequential programming code into independent reusable functions .

3. Functions can be used in other processes and reused by other components .

4. Better readability than callback functions .

5. Better error handling than sequential programming .

Of course , We can also better combine the advantages of sequential programming readability with the advantages of non blocking scalability . To be continued ..

[ The quilt banq On 2014-05-15 10:03 A modified ]

[ The quilt admin On 2014-05-15 14:24 A modified ]

[ The quilt admin On 2014-05-16 08:30 A modified ]

本文为[Jiedao jdon]所创,转载请带上原文链接,感谢

  1. JS: event flow
  2. Front end performance optimization: rearrangement and redrawing
  3. JS - deep and shallow copy
  4. JavaScript异步编程3——Promise的链式使用
  5. JavaScript asynchronous programming 3 -- chain use of promise
  6. Vue.js组件的使用
  7. The use of vue.js component
  8. How to judge whether a linked list has links
  9. Element UI custom theme configuration
  10. Text image parallax effect HTML + CSS + JS
  11. Spring的nohttp宣言:消灭http://
  12. Vue3 intermediate guide - composition API
  13. Analysis of URL
  14. These 10 widgets that every developer must know
  15. Spring's nohttp Manifesto: eliminate http://
  16. Learn more about JS prototypes
  17. Refer to await to JS to write an await error handling
  18. A short article will directly let you understand what the event loop mechanism is
  19. Vue3 uses mitt for component communication
  20. Characteristics and thinking of ES6 symbol
  21. Two way linked list: I'm no longer one-way driving
  22. Vue event and form processing
  23. Reactive TraderCloud实时外汇开源交易平台
  24. Reactive tradercloud real time foreign exchange open source trading platform
  25. Node.js REST API的10个最佳实践
  26. Ten best practices of node.js rest API
  27. Fiddler advanced usage
  28. Process from Vue template to render
  29. Promise up (asynchronous or synchronous)
  30. Principle and implementation of promise
  31. Vs code plug in sharing - run code
  32. Vue practical notes (1) introduction of Ant Design
  33. Vue actual combat notes (2) introduction of element plus
  34. Introduction to webpack
  35. Webpack construction process
  36. Vue notes
  37. The experience and lessons of moving from ruby megalith architecture to go microservice
  38. Using leancloud to add artitalk module to hexo blog
  39. Implementation of chrome request filtering extension
  40. Detailed introduction of beer import declaration elements and label quarantine [import knowledge]
  41. Gallop workflow engine design series 01 process element design
  42. VUE移动端音乐APP学习【十六】:播放器歌词显示开发
  43. Vue Mobile Music App learning [16]: player lyrics display development
  44. jquery cookie
  45. jquery cookie
  46. 体面编码之JavaScript
  47. JavaScript for decent coding
  48. React17 系统精讲 结合TS打造旅游电商平台
  49. React17 system combined with TS to build tourism e-commerce platform
  50. 2021-05-04 hot news
  51. HttpSession对象与Cooike的关系 以及 Cookie对象构造函数问题
  52. gRPC-Web:替代REST的gRPC的Javascript库包
  53. The relationship between httpsession object and cooike and the construction of cookie object
  54. Grpc Web: a JavaScript library package to replace rest grpc
  55. Building reactive rest API with Java - kalpa Senanayake
  56. PDF转HTML工具——用springboot包装pdf2htmlEX命令行工具
  57. Pdf to HTML tool -- Wrapping pdf2htmlex command line tool with springboot
  58. PDF转HTML工具——用springboot包装pdf2htmlEX命令行工具
  59. Pdf to HTML tool -- Wrapping pdf2htmlex command line tool with springboot
  60. Vue.js比jQuery更容易学习