推迟在node.js中执行asynchronous消息传递函数

我有一系列经过解码的多段线返回的纬度/经度对。

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

pubnub.publish()是一个asynchronous函数,我需要在每一步通过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); }); 

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函数的定义。 我相信如果你不为每个迭代定义函数,它会更有性能。 希望这可以帮助。