Posts Tagged ‘Asynch’

The two common asynchronous control flow patterns include sequential and parallel flows.

In the sequential flow, the tasks are executed one after the other in sequence and delay in one causes a delay in the start of the subsequent tasks.These can be a set of independent tasks without sharing any data among them or, they can be chained where the output of the preceding task is used as the input of the subsequent one (waterfall or, pipeline).

image

In parallel flow, the tasks are executed in parallel not in any specified order.

image

The above control flows can be implemented very easily using the async library. The three important functions that we will explore are:

  • async.series
  • async.parallel
  • async.waterfall

The async.series function accepts two arguments:

a) tasks – This can be array of functions or an object

b) callback – This is the optional callback function with two arguments error, results. The results parameter is an array which contains the result argument passed to the callback by each of the tasks.

In the code below we have three functions passed as the first argument and the callback function simply prints the elements of the result array passed to the callback.

image

The output will be as follows:

image

If we increase the timeout interval in the second function to 200 ms then the start of the third function is delayed. This clearly indicates the sequential execution.

image

I will now use the same code but I will invoke async.parallel instead of series.

image

The below output clearly shows that tasks are started and running simultaneously.

image

Now we will explore the async.waterfall function. This function also like series executes the tasks / functions sequentially but output of one function is passed as input to the next as shown below:

image

The output will be:

image