Understanding of async.whilst in node

Posted By : Pulkit Chadha | 28-Sep-2016

Understanding of async.whilst in Node

In this blog I am going to explain how you can use async.whilst.

Introduction:
whilst is one of the function of async module which help in working with asynchronous behaviour of javascript.whilst function is like a while loop of asynchrnous requests.If any of the condition pass an error to their callback, the  sequence will stop. Further iteration will not execute and the main callback is  called with the error.

Syntax: 

whilst(test, fn, callback)

Step 1: First, install async package in your node application using the commmand:

              npm install  async
        

Step 2: Suppose, we want to delete multiple files in the system.we can do this using async.whilst:

var fs = require('fs');

var filePathArray=['file1.txt','file2.txt','file3.txt','file4.txt','file5.txt'];

var count = 0;// initialize a variable.

async.whilst(
    function () { return count < filePathArray.length; },//check condition.
    function (callback) {
        fs.unlink(path, function (err) {
            if (err) {
            callback(err,null); // if error occurs
            } else {
                count++;
                callback(null, null);
            }
        });
    },
    function (err, n) {    //final result
        if(err){
            console.log("Some error occured');
        }else{
            console.log("All files deleted');
        }
);
            
        

THANKS

About Author

Author Image
Pulkit Chadha

Pulkit is an expert web app developer and has good knowledge of JQuery, MongoDb, NodeJs, AngularJS, kaltura, Akamai. etc.

Request for Proposal

Name is required

Comment is required

Sending message..