Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js async.whilst() is not executing at all

I'm just trying to use async.whilst() as seen here.

Here is my simple code, taken from their docs:

var async = require('async');

console.log('start');
async.whilst(
  function () { return true; },
  function (callback) {
    console.log('iteration');
    callback();
  },
  function (err) {
    console.log('end');
  },
);

When I run this, the loop doesn't run. Only start is printed out.

like image 285
Unconventional Wisdom Avatar asked Sep 03 '25 15:09

Unconventional Wisdom


1 Answers

Because you are returning true, that why the callback for function 1 wasn't called. So you only see the 'start'. You can find some information below:

    const async = require('async');
    let count = 0;
    const compareVariable = 10;
    console.log('start');
    async.whilst(
        function functionName1(callbackFunction) {
            // perform before each execution of iterFunctionInside, you need a condition(or other related condition) in 2nd params.
            callbackFunction(null, count < compareVariable)
        },
        // this func is called each time when functionName1 invoked
        function iterFunctionInside(callback) {
            // increase counter to compare with compareVariable
            count++;
            console.log('iteration', count);
            // if you want to show like tick time, you can set timeout here or comment out if you dont want
            setTimeout(() => {
                callback(null, count);
            }, 1000)
        },
        function (err, n) {
            console.log('end');
        },
    );
like image 71
Thang. Lam Duc Avatar answered Sep 05 '25 04:09

Thang. Lam Duc