在Redux Action中轮询

时间:2019-09-11 22:04:21

标签: javascript reactjs react-native redux polling

我正在尝试在我的一个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 });
};

任何帮助都会有用!

1 个答案:

答案 0 :(得分:1)

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