When and How to use ASYNC forEach in node.js

In node.js we need to use database, file read/write, upload files frequently. But while using these we don't know which one of them(if multiple event occurs) will be going to end first. Sometimes we need them to execute all db query or file read operations one by one, but node.js does not support this.

For solving this problem we can use async. And by using this we can turn our code clean from messed up callback hell.

In the beginning:

Here I'm using some topics without any references. Like,

  • To use async in your code you have to use var async = require('async');
  • Files is an imaginary module to grab info from Files collection of any NoSQL database. I take this format from database model info from sails model. `

To get more info about these check the links above.

How to use:

Let's check the example. By breaking the examples we can findout easily how to use async.forEach.

async.forEach(testFile, function (item, callback2) {
    Files.create({
        name: item.name,
        size: item.size
    }).done(function (errors, status) {
        //error handling
        if (status) {
            Access.create({
                file_id: status.id,
            }).done(function (accessError, accessDone) {
                if (accessDone)
                    callback2();
            });
        }
    })
});

Here we are taking a variable textFile which contains an array to which we to put in the database.
Then we place them into forEach and iterate them as a item.
After creating a single db entry, we grab their ID and run another db insertion. After successful insertion operation we call back the function which we placed into the forEach.
The main key feature is forEach will wait till all the operations are completed inside a single iteration.

comments powered by Disqus