jmcgrath207
jmcgrath207

Reputation: 2047

Nodejs Asynchronous Programming - why there is "async" module required? What is "Callback Hell" / "Pyramid of Doom"?

One of NodeJS's greatest features is that it is asynchronous out of the box from what I am reading, however as a beginner to NodeJS it's kind of confusing why modules like async exist if this is already being handled natively?

https://www.npmjs.com/package/async

I assume there is a good reason why but it's not obvious to me. Is it to handle callback hell or Pyramid of Doom.

Upvotes: 3

Views: 442

Answers (2)

Aruna
Aruna

Reputation: 12022

When you use asynchronous programming in NodeJS, you may end up with Callback Hell or Pyramid of Doom when you have more number of asynchronous functions to be called one after another one as below.

Callback - Once your first function is executed asynchronously, your main thread should be notified about it. For which you are passing a function as callback which will be fired once the asynchronous operation completes.

When you have more number of asynchronous functions in chain or inside a big loop, you may have to pass the same number of callbacks to find out the completion of each operation and the last one to perform other stuffs such as returning the response etc.

When you code them with more number of callbacks, it becomes very hard to manage/maintain and lacks better readability like the one below.

getData(function(a){  
    getMoreData(a, function(b){
        getMoreData(b, function(c){ 
            getMoreData(c, function(d){ 
                getMoreData(d, function(e){ 
                    ...
                });
            });
        });
    });
});

To get rid of these disadvantages and for better readability and maintenance, we may go with other modules such as async, bluebird etc. You can choose whatever you like which seems to be better for you in terms of understanding and satisfying all the requirements without making things too complex.

Anyways, this is purely up-to-you to go with the callback hell or other modules.

To get into the deeper insights,

https://strongloop.com/strongblog/node-js-callback-hell-promises-generators/

Upvotes: 2

Jaromanda X
Jaromanda X

Reputation: 1

Read the description:

Async is a utility module which provides straight-forward, powerful functions for working with asynchronous JavaScript.

It doesn't "provide" asynchronous functions, it provides functions for working with asynchronous javascript.

Note: javascript is not all asynchronous, just the asynchronous parts are asynchronous.

To put it another way

async doesn't make nodejs asynchronous, it makes using asynchronous code simpler through its sugar coated goodness

Upvotes: 8

Related Questions