首页 > 解决方案 > 我正在等待来自服务器的响应,但希望在等待响应的 1 分钟后在 UI 中显示一些超时消息

问题描述

我正在等待来自服务器的响应以将任务添加到列表中(这发生在后台),但希望在 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 中花费的时间比预期更长的通知。这种方法正确吗?它正在完成这项工作,但我以前没有以这种方式使用过超时,我不知道这是否是正确的方法。

标签: javascriptreactjsreact-redux

解决方案


我将向您展示我使用返回时间的示例,fakePromise因此20000ms如果时间更长10000ms并且 Promise 尚未解决,它应该显示加载屏幕或您想要的任何内容。我正在使用 setIntervalstartDateendDate在每个间隔上更新,然后我们比较两个日期以检查它是否大于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:示例


推荐阅读