每2秒提取一次呼叫,但不希望请求堆积

时间:2019-04-04 17:59:53

标签: javascript asynchronous promise fetch

我正在尝试进行API调用,但我希望它每2秒重复一次。但是我担心,如果系统在2秒内没有收到请求,它将建立请求并继续尝试发送请求。我该如何预防?

这是我要尝试的操作formulabarcontrol

spreadsheetcontrol

然后我用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中做一些类似于结构的承诺,以确保提取工作已经完成,但无法正常进行。

3 个答案:

答案 0 :(得分:3)

  

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点)重新执行。因此它只是延长了发送时间。”

答案 1 :(得分:1)

您可以使用finallytry/catch添加到setTimeout中,而不使用setInterval

请注意,与使用网络套接字本身实时性更高的网络套接字相比,这种长时间的轮询会产生更多的服务器负载

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);
    } finally {
        // do it again in 2 seconds
        setTimeout(getMachineAction , 2000);
    }
};

getMachineAction()

答案 2 :(得分:0)

简单!只需存储当前是否正在发出请求,并存储计时器是否已跳闸而没有发送新请求。

let in_progress = false;
let missed_request = false;
const getMachineAction = async () => {
    if (in_progress) {
        missed_request = true;
        return;
    }
    in_progress = true;
    try {
        const response = await fetch('https://localhost:55620/api/machine/');
        if (missed_request) {
            missed_request = false;
            setTimeout(getMachineAction, 0);
        }
        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);
    } finally {
        in_progress = false;
    }
};

要开始间隔,您需要省略()

setInterval(getMachineAction, 2000);