1

I got know about this async module ,and everyone is talking about it. As I know below code will trigger the callback when 2 db calls is done.

async.parallel([
    function(){ dbcall() },
    function(){ dbcall() }
], callback);

But is it compulsory to use async module? if I wrap my code properly it can be async too. Like I wrote this in controller

var Token = require('../models/token');
Token.getAllTokens(owner, function(err,callback){
    var device_tokens = callback.token;
    GCM_call(device_tokens); //another ajax call
  });

Above code will work, I tested it, GCM_call will wait and run after getAllTokens. So why use async module? is it just to make the code more readable?

1
  • "But is it compulsory to use async module?" Not at all. It provides helper methods that can make working with multiple asynchronous calls easier. Commented Jun 11, 2016 at 1:34

1 Answer 1

1

So why use async module? is it just to make the code more readable?

To some degree, yes, to make it more readable. It provides some useful utilities to write more readable and more performant code.

But most importantly, because it's solving some common problems when using async functionality. You are showing an example where you used a single callback, where the async module example in the first code block is first waiting for some async stuff to finish, then calls the callback function. How would you solve this with vanilla js? If you know Promise API, you might say Promise.all([promise1, promise2, ...]). But what when you want to use something like async.series, where only a single task should be ran at a time? That's the case where you'll often see hacked up solutions, which became known as callback hell, where callbacks are nested one into another.

So you could create vanilla code solutions with use of Promise API and even simpler with adding use of async/await from future ECMAScript spec, but this library is saving you the hassle of repeating this every time you occur a problem described above.

Sign up to request clarification or add additional context in comments.

2 Comments

can be solve, just use nested callback of callback, it is doable the code is ugly.
@AliciaBrandon I have described that as callback hell. It smells of bad design. In time where Promise API works in all modern browsers and there are many polyfills and utilities to turn even non-promise APIs (e.g. node's fs) into Promises, there's no reason to create callback hell.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.