【问题标题】:Delaying execution of an async messaging function in node.js延迟 node.js 中异步消息传递函数的执行
【发布时间】:2015-09-29 12:12:18
【问题描述】:

我有一系列从解码的折线返回的 lat/lng 对。

使用forEach,我提取每个纬度/经度对并使用pubnub.publish(),将此数据发送到一个通道。

pubnub.publish() 是一个异步函数,我需要在 forEach 循环的每个步骤中延迟消息的发布。

我查看了很多关于 setTimeout 立即执行的答案,并尝试了以下不同版本,包括不将 setTimeout 包装在闭包中,但无法延迟发布 - 它只是尽快将它们全部发送尽其所能。

谁能指出任何明显的错误?

decodedPolyline.forEach(function (rawPoints) {

    var value = {
        lat: rawPoints[0],
        lng: rawPoints[1]
    };

    var sendmsg = function () {
        pubnub.publish({
            channel: id, 
            message: value,
            callback: function (confirmation) {
                console.log(confirmation);
            },
            error: function (puberror) {
                console.log('error: ' + puberror);
            }
        });
    };

    (function() {
        setTimeout(sendmsg, 2000);
    })();

    normalised.push(value);
});

【问题讨论】:

  • 您是否尝试在每次调用 pubnub.publish 之间延迟 2 秒?现在,您的代码在未来将所有内容排队等待 2 秒,因此它们将在 2 秒后几乎同时执行。
  • @aframe 这个问题看起来像是一致消息队列的经典实现。
  • @nderscore - 我试图每两秒发布一次,是的。接受的答案完成了工作。

标签: javascript node.js asynchronous closures pubnub


【解决方案1】:

forEach 循环将近乎实时地执行,这意味着所有超时将几乎同时完成,您应该在每次迭代中将超时值增加 2000;也许这对你有用:

var sendmsg = function (value) {
    pubnub.publish({
        channel: id, 
        message: value,
        callback: function (confirmation) {
            console.log(confirmation);
        },
        error: function (puberror) {
            console.log('error: ' + puberror);
        }
    });
};

var timeoutVal = 2000;
decodedPolyline.forEach(function (rawPoints) {

    var value = {
        lat: rawPoints[0],
        lng: rawPoints[1]
    };

    (function(value) {
        setTimeout(function() {
            sendmsg(value);
        }, timeoutVal);
    })(value);

    //Add 2 seconds to the value so the next iteration the timeout will be executed 2 seconds after the previous one.
    timeoutVal = timeoutVal + 2000;

    normalised.push(value);
});

我还将sendmsg 函数的定义移到了循环之外。我相信,如果您不为每次迭代定义函数,它的性能会更高一些。希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-12-14
    • 1970-01-01
    • 2019-07-18
    • 1970-01-01
    • 2018-10-25
    • 1970-01-01
    • 2014-09-27
    • 2011-03-27
    相关资源
    最近更新 更多