【问题标题】:I am waiting for a response from the server, but want to show some timeout message in the UI after 1 minute while waiting for the response我正在等待来自服务器的响应,但希望在等待响应的 1 分钟后在 UI 中显示一些超时消息
【发布时间】:2020-08-06 18:34:14
【问题描述】:

我正在等待来自服务器的响应以将任务添加到列表中(这发生在后台),但希望在 1 分钟后在 UI 中显示一些超时,并显示操作需要更长时间的消息超出预期,服务器的响应最终可能是成功或失败。

Q.when(api.getTask(taskId))
        .then(function(data) {
            dispatch({type:'GET_TASK_REQUEST', data});   
        }).then(function() {
            Notify.showSuccess('Get task was a success');
            dispatch({type: 'GET_TASK_SUCCESS'});
        }).fail(function(error) {
            Notify.showError(error);
            dispatch({type: 'GET_TASK_FAILURE'});
        });

    setTimeout(() => {
        if(isLoading)
            dispatch({type: 'GET_TASK_TIMEOUT'});
    }, 60 * 1000);

基于在服务器仍未返回响应时调度的 GET_TASK_TIMEOUT 操作,我将状态设置为在 UI 中显示操作花费比预期更长的时间的通知。这种方法正确吗?它正在完成这项工作,但我以前没有以这种方式使用过超时,我不知道这是否是正确的方法。

【问题讨论】:

  • 你为什么不使用内联加载器?使用异步等待从 useEffect 调用 API 并显示加载程序或一些消息,直到您从 API 获取数据。
  • 我在等待响应时在 UI 中显示加载程序。我想要做的是,如果某个时间过去了,在这种情况下为 60 秒,我只想显示一个通知,表明它需要时间并且不取消。

标签: javascript reactjs react-redux


【解决方案1】:

我将向您展示我使用fakePromise20000ms 返回时间的示例,因此如果时间大于10000ms 并且Promise 尚未解决,它应该显示加载屏幕或您想要的任何内容。我将 setInterval 与 startDateendDate 一起使用,每个间隔都会更新,然后我们比较两个日期以检查它是否大于 10000ms 这是代码:

   const fetchData = async () => {
  try {
    const sDate = new Date();
    let endDate;
    const LoadingResponse = setInterval(() => {
      if (endDate && endDate.getTime() - sDate.getTime() > 10000) {
        setLoading(true);
        clearInterval(LoadingResponse);
      } else endDate = new Date();
    }, 1000);
    const data = await fakePromise();
    clearInterval(LoadingResponse);
    setData(data);
  } catch (error) {
  } finally {
    setLoading(false);
  }
};

这里是codeSandbox:example

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-05
    • 2016-04-20
    • 2013-10-25
    • 2015-05-22
    • 2015-03-02
    • 1970-01-01
    相关资源
    最近更新 更多