英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论