javascript - Redux Action 中的轮询
问题描述
我正在尝试在我的一项 redux 操作中进行轮询。以下是我的动作函数。它似乎正在工作,但是当状态不再“更新”并且数据出现时,它仍然运行循环。不知道为什么停止不起作用。
export const getVisitSummary = () => async (dispatch: Function) => {
let res = await dispatch({
type: GET_VISIT_SUMMARY,
payload: {
client: 'visitSummary',
request: {
method: 'get',
url: '/visit-summaries'
}
}
});
const timelineStatus = res.payload.headers['x-timeline-status'];
const wait = (ms: number) => new Promise(r => setTimeout(r, ms));
// Not currently updating
if (timelineStatus !== 'updating') {
return res;
}
// Start polling
dispatch({ type: START_POLLING });
while (true) {
// wait 10 seconds
await wait(10000);
res = await dispatch({
type: GET_VISIT_SUMMARY,
payload: {
client: 'visitSummary',
request: {
method: 'get',
url: '/visit-summaries'
}
}
});
if (timelineStatus !== 'updating') {
break;
}
}
dispatch({ type: STOP_POLLING });
};
任何帮助都会很有用!
解决方案
将@azundo 的评论翻译成答案:
export const getVisitSummary = () => async (dispatch: Function) => {
let res = await dispatch({
type: GET_VISIT_SUMMARY,
payload: {
client: 'visitSummary',
request: {
method: 'get',
url: '/visit-summaries'
}
}
});
/***************************************/
/*** 1: Change from `const` to `let` ***/
/***************************************/
let timelineStatus = res.payload.headers['x-timeline-status'];
const wait = (ms: number) => new Promise(r => setTimeout(r, ms));
// Not currently updating
if (timelineStatus !== 'updating') {
return res;
}
// Start polling
dispatch({ type: START_POLLING });
while (true) {
// wait 10 seconds
await wait(10000);
res = await dispatch({
type: GET_VISIT_SUMMARY,
payload: {
client: 'visitSummary',
request: {
method: 'get',
url: '/visit-summaries'
}
}
});
/*********************************************************/
/*** 2: Use updated `timelineStatus` in if conditional ***/
/*********************************************************/
timelineStatus = res.payload.headers['x-timeline-status'];
if (timelineStatus !== 'updating') {
break;
}
}
dispatch({ type: STOP_POLLING });
};
推荐阅读
- ssms - 使用 SSMS 2014,如何生成高效的插入脚本?
- azure - 如何在 MS Azure 中创建应用程序以使用 aws lex 在 Outlook Office 365 中安排约会
- php - 如何找出 Wordpress 页面的一部分的来源?
- azure - 无法使用 FTPS 将文件从 Azure 发布管道复制到服务器
- typo3 - 我在哪里实现我的 TYPO3 扩展的设置 html?
- batch-file - 批处理脚本回显可用驱动器错误
- python - Django:当我在使用时导入 Django 模型或函数时,Celery 会抛出错误
- android - 在 Android 上膨胀布局 XML
- spring - Elasticsearch 返回空的 json 对象
- nuxt.js - 使用 Amplify 和 Nuxt.js 强制登录页面