javascript - 发出Ajax请求时如何只等待1秒,但等待时间后不取消请求?
问题描述
我有一种情况,如果 ajax 请求在 1 秒内没有返回,我必须返回 false。但是在请求完成后处理响应。使用 Ajax 超时对我不起作用,因为它会在该时间之后取消请求。但即使需要很长时间,我也希望得到回应。
例子:
function call(){
ajax.request(...)
if(does not respond in 1 second)
immediately return false and wait for response
else
return response
}
解决方案
您需要在请求完成和错误处理程序之间设置竞争。如果请求首先完成,请在处理错误之前设置一个您检查的标志:
function call(){
let finished = false;
function callback(){
finished = true
// your callback code goes here
};
ajax.request(..., callback) // make sure this is an async request
function handleTimeout() {
if (finished) return;
// your timeout code goes here
}
setTimeout(handleTimeout, TIMEOUT_IN_MILLISECONDS);
}
或者设置一个标志,你可以取消 timeout。
请注意,您的call
函数不会返回任何内容。相反,您基本上处理事件(请求完成或超时到期中的一个或两个)。
推荐阅读
- php - 如何在 php 中访问本地 JSON 数组?
- python - 如何遍历 JSON 列表以仅查找我网站的 URL?
- python - 可以将两个逻辑表达式合二为一
- reactjs - Netlify / Gatsby / React - 我需要以“?&”开头的页面
- rxjs - 无法在 playcode 代码沙箱中使用 rxjs
- dictionary - 如何从字典中获取无效的 Tcl 值并针对整数进行测试?
- spring-boot - 无法让此控制器返回具有正确 mime 类型的文件
- reactjs - 将异步函数放入 useEffect 后出现错误
- javascript - 通过来自 woocommerce HTML 变体的数据集生成 JS 变量数组
- c# - Windows SC.exe如何查询服务的控制码