我在无限循环内调用 sqs.receiveMessage(receiveParams, function(err, data){})
。但它根本没有被触发。
var receiveParams = {
QueueUrl: queueUrl,
VisibilityTimeout: 40
};
while (true)
{
console.log("before");
setTimeout(function() {
sqs.receiveMessage(receiveParams, function(err,data){
console.log("Calling");
if (err) {
console.log(err);
}
else {
console.log(data);
if (data.Messages != null)
{
console.log("Executing my fuction");
myFunction();
}
}
});
}, 10000);
console.log("after");
}
如果我在循环外执行sqs.receiveMessage()
,它工作正常。我不知道为什么它永远不会在循环中被调用。我猜我的超时设置有问题。因为我的循环将记录“之前”和“之后”而没有时间延迟。有什么帮助吗?
最佳答案
您的代码正在用无限数量的 setTimeout
命令淹没 Node 事件堆栈。
也就是说,在代码运行时,它将首先生成一个任务来执行 sqs.receiveMessage
调用 - 它会在一秒钟后执行该任务。然而,在第一个任务启动之前,在 while
循环的第二次迭代中,它将再次生成另一个类似的任务。因此,在一秒钟的时间范围内,您将有大约一千个这样的任务,这些任务的启动时间可能相隔 1 毫秒。这解释了为什么您会看到这些指纹。
您没有从服务获得正确响应的原因可能是它启用了“洪水保护”。例如。如果在一定时间内来自同一调用者的请求太多,那么它将在 X 时间内忽略该调用者。
您可能想使用setInterval
。
参见https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setInterval
setInterval
Repeatedly calls a function or executes a code snippet, with a fixed time delay between each call. Returns an intervalID.
示例:
// repeat the call every 10seconds
setInterval(function() {
sqs.receiveMessage(receiveParams, function(err,data){
console.log("Calling");
if (err) {
console.log(err);
}
else {
console.log(data);
if (data.Messages != null)
{
console.log("Executing my fuction");
myFunction();
}
}
});
}, 10000);
让我知道你是如何处理的。如果需要的话,很乐意提供进一步的帮助。
关于javascript - 无限循环中无法接收来自SQS的消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38111831/