Javascript的setInterval函数,在满足条件时退出。

huangapple go评论67阅读模式
英文:

Javascript setInterval function, escaping on condition

问题

此代码的功能是定期向服务器请求处理是否完成(在这种情况下,使用Python和Flask生成文本到图像),每秒一次。一旦收到'done'响应,它应该立即停止请求并继续下一步(这是一个类似表单向导的React应用程序)。我已经检查了开发者工具中的浏览器网络选项卡,响应是正确的(在处理完成后更改为'done'),但它不会移动到下一步,也不会停止请求。

"我只需要这个axios.get在收到'done'响应后立即停止。"

英文:
const getDataFromServer = async () => {
    var response = setInterval(()=> {
        var w = axios.get('/yet')
        if(w.data === 'done') {
            nextStep();
            clearInterval(response)
        }
    }, 1000);
};

`What this code does is that It keeps asking the server if the processing(In my case it's text to image generation using python,flask) is done yet.(every secend) And as soon as it gets 'done' response It should stop asking immediately and move on to the next step(it's form-wizard-style react app). I checked the browser's network tab in the developer tool and the response was correct(changed to 'done' after the process has been done) but it doesn't move to the next step and doesn't stop asking.

I just need this axios.get to stop as soon as it gets 'done' response.

答案1

得分: 3

我非常确定axios.get返回一个Promise,所以w变量实际上是一个Promise对象,而不是响应。你可以尝试像这样改写:

const getDataFromServer = () => {
   const interval = setInterval(async () => {
        const w = await axios.get('/yet');

        if (w.data === 'done') {
            nextStep();
            clearInterval(interval);
        }
    }, 1000);
}

另请参阅关于Promises的MDN页面

英文:

I am pretty sure the axios.get returns a promise, so the w variable is actually a promise object and not the response. You can try something like this instead.

const getDataFromServer = () => {
   const interval = setInterval(async () => {
        const w = await axios.get('/yet');

        if (w.data === 'done') {
            nextStep();
            clearInterval(interval);
        }
    }, 1000);
}

See also the MDN page about promises.

huangapple
  • 本文由 发表于 2023年6月18日 22:47:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/76501111.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定