📜 ⬆️ ⬇️

Analogue of the Step Pattern and Asynchronous Call Nesting

When implementing a model for manipulating data in MongoDB, I came to the conclusion that you need to somehow avoid problems with asynchronous nesting. I did not know about the existence of Step for Node.js and decided to create my own bike. What I would like to share with you, dear Habro users.


Introduction


In order to solve the problem of calls and the further transfer of information to the next call in the queue, the AQueue module (implementation of a sequential queue of asynchronous calls) was born. In the implementation of this module, lies the principle applied in the implementation of the intermediate routing layer in Express.js (for example, to test the accessibility of a particular view). This mechanism is implemented by calling a callback function called next () with passing it the necessary parameters.
')
And so let's get started!

Implementation


For queuing, an array was selected in which the functions are written, in the sequence in which they will be called.


  1. function AQueue ( ) {
  2. var that = this ;
  3. that. q = [ ] ;
  4. that. cb = null ;
  5. that. addTo = function ( f ) {
  6. that. q . push ( f ) ;
  7. return that ;
  8. } ;
  9. that. next = function ( err , data ) {
  10. if ( that. q . length > 0 ) {
  11. var f = that. q . shift ( ) ;
  12. if ( err ) {
  13. that. q = [ ] ;
  14. that. cb ( err , data ) ;
  15. } else {
  16. f ( that. next , err , data ) ;
  17. }
  18. } else {
  19. that. cb ( err , data ) ;
  20. }
  21. } ;
  22. that. completed = function ( cb ) {
  23. that. cb = cb ;
  24. return that ;
  25. } ;
  26. that. run = function ( ) {
  27. return that. next ( null , null ) ;
  28. } ;
  29. }
  30. exports. AQueue = AQueue ;


Using


Below is an example of using the AQueue module.

  1. var AQueue = reqiure ( 'aqueue' ) . AQueue ;
  2. var aq = new AQueue ( ) ;
  3. aq. addTo ( function ( next , err , data ) {
  4. // make the necessary actions
  5. next ( err , data ) ;
  6. } ) . addTo ( function ( next , err , data ) {
  7. // perform additional actions
  8. // you can combine data by wrapping it in an object
  9. next ( err , { data : data , checked : true } ) ;
  10. } ) . completed ( function ( err , data ) {
  11. // perform final actions.
  12. } ) . run ( ) ;

Source: https://habr.com/ru/post/139748/


All Articles