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.
The AddTo function - adds the next function to the queue.
The function next - allows you to call the next in order function.
Function completed - called upon successful completion, or when the err parameter is not null
The run function starts the call mechanism in turn.
The q property is used to store functions in an array.
The cb property is used to store call completion function.
function AQueue ( ) {
var that = this ;
that. q = [ ] ;
that. cb = null ;
that. addTo = function ( f ) {
that. q . push ( f ) ;
return that ;
} ;
that. next = function ( err , data ) {
if ( that. q . length > 0 ) {
var f = that. q . shift ( ) ;
if ( err ) {
that. q = [ ] ;
that. cb ( err , data ) ;
} else {
f ( that. next , err , data ) ;
}
} else {
that. cb ( err , data ) ;
}
} ;
that. completed = function ( cb ) {
that. cb = cb ;
return that ;
} ;
that. run = function ( ) {
return that. next ( null , null ) ;
} ;
}
exports. AQueue = AQueue ;
Using
Below is an example of using the AQueue module.
var AQueue = reqiure ( 'aqueue' ) . AQueue ;
var aq = new AQueue ( ) ;
aq. addTo ( function ( next , err , data ) {
// make the necessary actions
next ( err , data ) ;
} ) . addTo ( function ( next , err , data ) {
// perform additional actions
// you can combine data by wrapping it in an object