01 – Exploring async.js: async.parallel

Share:
Source Code

About This Series

In “Exploring async.js”, we’re going to learn about async.js, the jQuery of Nodejs.

Async.js is a utility module which provides straight-forward, powerful functions for working with asynchronous JavaScript. Although originally designed for use with Node.js and installable via npm install async, it can also be used directly in the browser.

https://github.com/caolan/async

Let’s start off the series with one of the most useful functions of async.js called async.parallel

Our tutorial will be executed from node.js environment, so be sure to have node.js installed on your computer.

Create a package.json file to specify our dependencies for the project, you can use the default npm init command to help you fill it out:

{
  "name": "tutorial-async",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "async": "^1.4.0",
    "github": "^0.2.4",
    "lodash": "^3.10.1"
  }
}

then run

npm install  

and finally, create an index.js file and we’re ready to begin!

Let’s briefly go over what the function signature of async.parallel look like:

async.parallel(tasks, [callback])  

where tasks is an array of functions, and callback is a function that gets executed at the end of the execution of all the functions in the array. All tasks are executed concurrently or in parallel, and if any of the function produces an error, the execution immediately stops and callback gets invoked.

Array notation

Okay, first we need to edit our index.js file.

We need to bring in async.js library by requiring it:

var async = require('async');  

then we create an array of functions:

//With Array
var stack = [];

var functionOne = function(callback) {  
    callback(null, 'First function result');
}

var functionTwo = function(callback) {  
    callback(null, 'Second function result');
}

var functionThree = function(callback) {  
    callback(null, 'Third function result');
}

stack.push(functionOne);  
stack.push(functionTwo);  
stack.push(functionThree);  

and finally, pass the array to async.parallel:

async.parallel(stack, function(err, result) {  
    console.log('Async parallel with array', result);
});

Within each function of the array, there’s a parameter call callback passed in, this is the function async.parallel checks for during in each function execution.

The signature of that callback function is:

callback(error, result);  

where error is an object or string you pass to it to signal a failure (example: 500 error response, or file not found), and this will immediately make async.parallelexit its execution loop and invoke the final callback we mentioned earlier.

Let’s see what this code does:

node index.js  

and we can see output of this program is an array containing results computed from each functions in the stack:

[
   'First function result',  
   'Second function result',  
   'Third function result'  
]

Handling errors

To simulate an error, let’s change functionOne to

var functionOne = function(callback) {  
    callback('ERROR HAPPENED!', null);
}

run it, and you’ll see:

[null]

this means the execution stopped prematurely due to an error being passed to the callback of a function within the stack.

Object notation

Async.parallel works with object notation as well.

//With Object 
var stackObject = {};

stackObject.userName = function(callback) {  
    callback(null, 'Bob');
}

stackObject.age = function(callback) {  
    callback(null, '28');
}

stackObject.gender = function(callback) {  
    callback(null, 'Male');
}

async.parallel(stackObject, function(err, result) {  
    if (err) {
        console.error(err);
        return;
    }
    console.log('Async parallel with Object', result);
});

Here, we pass an object with list of functions as properties to async.parallel, so instead of returning an array of results, async.parallel will return an object with name of the functiosn as keys, and results of each function as value:

{
    {userName: 'Bob'}, {age: '28'}, {gender: 'Male'}
}

Nifty!

That is it for our quick intro to some of the most useful functions from async.js Visit the Youtube playlist for a list of other not so common but useful functions:

Comments Or Questions? Discuss In Our Discord

If you enjoyed this tutorial, make sure to subscribe to our Youtube Channel and follow us on Twitter @pentacodevids for latest updates!

More from PentaCode