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 秒获取一次调用,但不希望请求堆积
基础教程推荐
- Electron 将 Node.js 和 Chromium 上下文结合起来意味着 2022-01-01
- 如何使用TypeScrip将固定承诺数组中的项设置为可选 2022-01-01
- Chart.js 在线性图表上拖动点 2022-01-01
- 直接将值设置为滑块 2022-01-01
- html表格如何通过更改悬停边框来突出显示列? 2022-01-01
- 用于 Twitter 小部件宽度的 HTML/CSS 2022-01-01
- 如何使用JIT在顺风css中使用布局变体? 2022-01-01
- 我可以在浏览器中与Babel一起使用ES模块,而不捆绑我的代码吗? 2022-01-01
- 自定义 XMLHttpRequest.prototype.open 2022-01-01
- Vue 3 – <过渡>渲染不能动画的非元素根节点 2022-01-01