每2秒提取一次呼叫,但不希望请求堆积 [英] Fetch call every 2 seconds, but don't want requests to stack up

查看:51
本文介绍了每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秒提取一次呼叫,但不希望请求堆积的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆