Habilelabs-Logo
Blog

Avoid callback hell using Async module

May 4th, 2017 . 3 minutes read
Blog featured image

In this article, we will discuss some methods to avoid callback hell with the simple async module.  let’s start with a callback.

The callback is an asynchronous equivalent for a function. A callback function is called at the completion of a given task. Node makes heavy use of callbacks. All the APIs of Node are written in such a way that they support callbacks.
E.g. – downloading images, reading files etc.

When you call a normal function can use return values:

Functions that use callbacks don’t return anything right away.

var image = downloadImage(‘http://google.com/flower.gif’)
In this case, the gif image takes a long time to download, and you don’t want the program to pause while waiting for the download to finish.

In this example, downloadImage function is invoked and passed the handleImage its callback, and finally ‘Downloading started’ is printed out.
handleImage passed as a callback in downloadImage. Until downloadImage finish doing its task, which could take a long time depending on how fast the Internet connection is.

How do I fix callback hell?

Callback hell is caused by the poor coding practice. let’s start how to avoid callback hell.

E.g: – It is looking like a pyramid.

 

You can avoid callback hell using the async module:

Async is a utility module which provides straight-forward, powerful functions for working with asynchronous JavaScript.
It is designed for use with Node.js and installs via npm install –save async.

There are 3 methods in async.

1. series() method:

The series() method takes an array of functions as an argument. The functions are executed in the order in which they exist in the array.
Each callback function in the list takes the err parameter as the first argument to the function, and the second argument is the return value.series() waits for one function to finish before executing the next one.

Execution of this code is blogData1 finish first then blogData2 and finally blogData3.

2.parallel() method:

async.parallel() method to perform parallel-like executions of your callbacks.

Execution of this code is the result of function 1 and function 2 is parallel.

3. waterfall() method:

The waterfall() method is useful when you need the results of a previous function to perform an operation with the next
function in the series.

E.g.-

waterfall method similar to series method but we can pass a variable in a function.

Discuss with us if you have any query related to callback hell in the comment box. We are web app development experts, contact us if you have anything amazing to build in mind.

Share this post with your friends, if you found this helpful.

Author: divya
Share: