gpt4 book ai didi

javascript - Redux Action 中的轮询

转载 作者:行者123 更新时间:2023-12-02 22:58:07 25 4
gpt4 key购买 nike

我正在尝试在我的一项 Redux 操作中进行轮询。以下是我的 Action 函数。它似乎有效,但是当状态不再“正在更新”并且数据出现时,它仍然运行循环。不知道为什么停止不起作用。

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 });
};

关于javascript - Redux Action 中的轮询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57897378/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com