Pergunta

I am using async.js to do the following:

var async = require('async');
var i = 0;
var continueWhilst = true;
async.whilst(
  function test() { return continueWhilst; },
  function doThisEveryTime(next) {
    i++;
    if (i===5) {
      continueWhilst = false;
    }
    console.log(i);
    next();
  },
  function (err) {
    // Done
  }
);

The above worked. This is the documentation for async.whilst.

Now I wanted to abstract out the doThisEveryTime function so the code's much readable. I tried doing this:

var i = 0;
var continueWhilst = true;
async.whilst(
  function test() { return continueWhilst; },
  doThisEveryTime2(next),
  function (err) {
    // Done
  }
);

function doThisEveryTime2(next) {
  i++;
  if (i===5) {
    continueWhilst = false;
  }
  console.log(i);
  next();
}

But it didn't work. The error message is as follow:

  doThisEveryTime2(next),
               ^
ReferenceError: next is not defined

How do I do this correctly?

Foi útil?

Solução

You need to only pass the doThisEveryTime function, not call it - no parenthesis, no next:

var i = 0;
var continueWhilst = true;
async.whilst(
  function test() { return continueWhilst; },
  doThisEveryTime2,
  function (err) {
    // Done
  }
);

Also notice that you rather should use the timesSeries function for what you are doing - with the additional benefit that i is a functional argument to the doThisEveryTime function, not a global variable.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top