我的 Node 应用程序中有一个模块,其中有一个 setTimeout 函数,该函数每隔 60 分钟调用一次。为了简单起见,您可以理解为每 60 分钟后,
- 它连接到某个云
- 从中查询一些数据
并将其保存在我的 Mongo 集合中
setTimeout(() => { fetchData(); }, 3600000); // = 1 hour
问题是,如果 fetchData
函数中出现任何错误,那么我会抛出一个错误,并且服务器的代码流会停止,并且显然 setTimeout 永远不会再次启动。
throw new Error(err);
可能的错误方式:
- 登录云端
- 通过某些查询获取数据
- 从云端注销以及更多
所以,我需要某种解决方案,在抛出错误后我可以重新启动此 setTimeout 函数,以便我的获取过程将继续进行。我不确定这是否可能,这就是我在这里发帖的原因。
还请注意,实际上,这个 fetchData
函数是一个由 10 多个文件和大量 JavaScript promise 组成的模块。
如果有人需要澄清,请在评论中告诉我。
最佳答案
这绝对是可能的。您需要正确处理错误。这可以通过一个简单的 try catch block 来实现:
function simulateError(){
return (Math.floor(Math.random() * 5) + 1) == 3;
}
function cloudConnect(){
if (simulateError()){
throw new Error("Cloud connect error");
}
else {
return "Connection";
}
}
function cloudQuery(){
if (simulateError()){
throw new Error("Query error");
}
else {
return "Query results";
}
}
function saveCollection(){
if (simulateError()){
throw new Error("Save error");
}
else {
return "Save results";
}
}
function fetchData(){
try {
cloudConnect();
cloudQuery();
saveCollection();
}
catch(error){
console.log("Error fetching data: ",error, " will retry in N seconds");
}
}
//Now that fetchData handles errors with a try/catch block, the interval will continue to run every 60 seconds,
//regardless of whether or not any errors are thrown
setInterval(function(){
fetchData();
}, 60000);
关于JavaScript 超时重启,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43120286/