我正在尝试进行 API 调用,并且希望它每 2 秒重复一次。然而,我担心如果系统在 2 秒内没有收到请求,它将建立请求并继续尝试发送它们。我怎样才能防止这种情况发生?
这是我正在尝试的操作fetch
:
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 中做一些类似承诺的结构,以确保提取已工作并完成,但无法使其工作。
The Promise.all()解决方案
此解决方案可确保您不会错过 2 秒延迟要求,并且在另一个网络呼叫正在进行时也不会触发呼叫。
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();
注意:这会按照问题作者的要求处理不良情况定义:
““坏情况”(即需要超过 2 秒)是我希望它跳过该请求,然后发送一个新请求。因此,在 0 秒时请求发送。执行需要 3 秒,然后需要 2 秒稍后(5 点)它应该重新执行。所以它只是延长了发送时间。”
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)