问题描述
我正在尝试进行 API 调用,我希望它每 2 秒重复一次.但是我担心如果系统在 2 秒内没有收到请求,它会建立请求并继续尝试发送它们.我怎样才能防止这种情况发生?
I am trying to make an API call and I want it to repeat every 2 seconds. However I am afraid that if the system doesn't get a request back in 2 seconds, that it will build up requests and keep trying to send them. How can I prevent this?
这是我尝试获取
的操作:
const getMachineAction = async () => {
try {
const response = await fetch( 'https://localhost:55620/api/machine/');
if (response.status === 200) {
console.log("Machine successfully found.");
const myJson = await response.json(); //extract JSON from the http response
console.log(myJson);
} else {
console.log("not a 200");
}
} catch (err) {
// catches errors both in fetch and response.json
console.log(err);
}
};
然后我用 setInterval
调用它.
function ping() {
setInterval(
getMachineAction(),
2000
);
}
我曾想过在 setInterval 中做一些类似结构的承诺,以确保获取已经工作并完成,但无法使其正常工作.
I have thought of doing some promise like structure in the setInterval to make sure that the fetch had worked and completed, but couldn't get it working.
推荐答案
Promise.all() 解决方案
此解决方案可确保您不会错过 2 秒延迟要求,也不会在另一个网络呼叫正在进行时触发呼叫.
This solution ensures that you don't miss-out on 2 sec delay requirement AND also don't fire a call when another network call is underway.
function callme(){
//This promise will resolve when the network call succeeds
//Feel free to make a REST fetch using promises and assign it to networkPromise
var networkPromise = fetch('https://jsonplaceholder.typicode.com/todos/1');
//This promise will resolve when 2 seconds have passed
var timeOutPromise = new Promise(function(resolve, reject) {
// 2 Second delay
setTimeout(resolve, 2000, 'Timeout Done');
});
Promise.all(
[networkPromise, timeOutPromise]).then(function(values) {
console.log("Atleast 2 secs + TTL (Network/server)");
//Repeat
callme();
});
}
callme();
注意:这会按照问题作者的要求处理不良案例定义:
Note: This takes care of the bad case definition as requested by the author of the question:
坏情况"(即需要超过 2 秒)是我希望它跳过该请求,然后发送一个新请求.所以在 0 秒时请求发送.需要 3 秒执行,然后 2 秒后(在 5)它应该重新执行.所以它只是延长时间直到它发送."
这篇关于每 2 秒获取一次调用,但不希望请求堆积的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!