如何在同步循环中使用setTimeout在Node.JS中?

3
我要实现的目标是一个不断定时发送数据的客户端。我需要让它无限运行。基本上它是一个模拟/测试类型的客户端。
我在使用setTimeout时遇到了问题,因为它是在同步循环内部调用的异步函数。结果就是data.json文件中的所有条目都同时输出。
但我想要的是:
  • 输出数据
  • 等待10秒
  • 输出数据
  • 等待10秒
  • ...
app.js:
var async = require('async');

var jsonfile = require('./data.json');

function sendDataAndWait (data) {
    setTimeout(function() {
        console.log(data);
        //other code
    }, 10000);
}

// I want this to run indefinitely, hence the async.whilst
async.whilst(
    function () { return true; },
    function (callback) {
        async.eachSeries(jsonfile.data, function (item, callback) {
            sendDataAndWait(item);
            callback();
        }), function(err) {};
        setTimeout(callback, 30000);
    },
    function(err) {console.log('execution finished');}
);

1
也许你可以使用 setInterval 代替? - user2428118
1个回答

2

您应该传递回调函数:

function sendDataAndWait (data, callback) {
    setTimeout(function() {
       console.log(data);
       callback();
       //other code
    }, 10000);
}

// I want this to run indefinitely, hence the async.whilst
async.whilst(
    function () { return true; },
    function (callback) {
       async.eachSeries(jsonfile.data, function (item, callback) {
           sendDataAndWait(item, callback);
       }), function(err) {};
      // setTimeout(callback, 30000);
    },
    function(err) {console.log('execution finished');}
);

1
谢谢!就是这样。该死的回调函数! :) - Nick
谢谢!是的,回调函数。 - wazhao

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接