Quantcast
Viewing latest article 5
Browse Latest Browse All 42

Asynchronous Control Flow in Node.js with async Library

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 may be NSFW.
Clik here to view.
image

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

Image may be NSFW.
Clik here to view.
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 may be NSFW.
Clik here to view.
image

The output will be as follows:

Image may be NSFW.
Clik here to view.
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 may be NSFW.
Clik here to view.
image

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

Image may be NSFW.
Clik here to view.
image

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

Image may be NSFW.
Clik here to view.
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 may be NSFW.
Clik here to view.
image

The output will be:

Image may be NSFW.
Clik here to view.
image


    Viewing latest article 5
    Browse Latest Browse All 42

    Trending Articles