Alicia Brandon Alicia Brandon - 5 months ago 11
Javascript Question

use of async module in node.js

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?

Answer

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.