async while not 运行 fn

async whilst not running fn

我想使用 async.whilst 函数,当我在输出中得到第一个 console.log 时,可能严重遗漏了一些东西。

// app.js 文件

var async = require('async');
var count = 0;

async.whilst(
    function () { 
      console.log('first')
      return count < 5; 
    },
    function (callback) {
      count++;
      console.log('second')
      callback()
    },
    function (err) {
      console.log('third')
    }
);

// 运行 脚本

$ node app.js
first
$

看看the documentation:第一个函数也需要一个回调

var async = require('async');
var count = 0;

async.whilst(
  function (callback) {
    console.log('first')
    return callback(null, count < 5);
  },
  function (callback) {
    count++;
    console.log('second')
    callback()
  },
  function (err) {
    console.log('third')
  }
);

您应该在 第一个函数 中使用 callbackasync 在调用 callback 时调用后续函数。你的代码应该是

async.whilst(
    function (cb) { 
      console.log('first')
      cb(null,count < 5); 
    },
    function (callback) {
      count++;
      console.log('second')
      callback()
    },
    function (err) {
      console.log('third')
    }
);