Understanding of async.whilst in node
Posted By : Pulkit Chadha | 28-Sep-2016

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
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Pulkit Chadha
Pulkit is an expert web app developer and has good knowledge of JQuery, MongoDb, NodeJs, AngularJS, kaltura, Akamai. etc.