我正在尝试进行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 函数中添加一些 promise 结构来确保 fetch 已经成功并完成,但是无法使其正常工作。
setTimeout
,在上一个完成后安排下一个2秒。 - zero298