Fetch call every 2 seconds, but don#39;t want requests to stack up(每 2 秒获取一次调用,但不希望请求堆积)
问题描述
我正在尝试进行 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 秒获取一次调用,但不希望请求堆积的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:每 2 秒获取一次调用,但不希望请求堆积
- Fetch API 如何获取响应体? 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- addEventListener 在 IE 11 中不起作用 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- 400或500级别的HTTP响应 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01