javascript - 我正在等待来自服务器的响应,但希望在等待响应的 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 中花费的时间比预期更长的通知。这种方法正确吗?它正在完成这项工作,但我以前没有以这种方式使用过超时,我不知道这是否是正确的方法。
解决方案
我将向您展示我使用返回时间的示例,fakePromise
因此20000ms
如果时间更长10000ms
并且 Promise 尚未解决,它应该显示加载屏幕或您想要的任何内容。我正在使用 setIntervalstartDate
并endDate
在每个间隔上更新,然后我们比较两个日期以检查它是否大于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:示例
推荐阅读
- robotframework - 如何检查数据是否显示在 html 表格中,否则如果数据未显示在表格中,则使用机器人框架将失败
- fp-ts - io-ts 嵌套类型实现
- c - 变量的声明和赋值在 K&R 中的不同行上是否有原因?
- css - 如何加载一个在 React 谷歌地图组件之上?
- c# - Collision2D对撞机/刚体的速度没有速度?
- python - 在 Python 脚本中,如何使流链接写入日志文件。>
- python - 随机森林和集成学习器给出了相似的准确度
- vscode-settings - 我对 VScode 中的终端有疑问
- c++ - 对于具有重复字符的字符串,字符串的排列失败
- apache-flink - Q.Apache Flink:在initializeState期间如何获取当前key