[英]How can I achieve javascript sync xmlhttprequest with timeout when it is not supported?
我在上下搜索了其他选择(Promise,异步调用等),但仍找不到可行的解决方案。
我有一个非常典型的情况,例如:
blockingCallBackFunctionFor3rdPartyLibraryAPI(url)
{
responseCode = cloudLookupCall(url); // async or sync call over the web
if (responseCode == "Deny")
{
// Return "Deny" URL decision to external library/API
}
// Return default "Allow" decision
}
function cloudLookupCall(url)
{
var hdl = new XMLHttpRequest();
hdl.open(method, url, true/false); // true/false based on async/sync
// use standard XHR stuff to get responseText
return responseText;
}
现在:
我只是不明白为什么JS实现决定在您似乎最需要同步的地方决定不支持同步调用的超时(以避免永久挂起浏览器)。
我已经阅读了很多论坛建议的Promise和异步回调,但请在上面说明为什么这些回调将不起作用-我需要立即采取措施,或者需要让JS等待的方法。 我也迫不及待地也没有采取行动。
在这一点上,我相当有信心地说,我坚持使用SYNC调用,但是要了解如何确保不永久阻塞SYNC(不是ASYNC的替代方案),这是什么现状。 使用set_time_limit()确保我的Web php处理程序超时在1秒内解决无限期挂起的问题吗?
如果可能,请尝试向cloudLookupCall()
添加function
作为参数:
function cloudLookupCall(func){
// your stuff here
// and when it's needed for you to callback
if (typeof func === 'function'){
func();
}
}
然后在您的脚本中:
responseCode = cloudLookupCall(function(data){
// continue here
});
如果那不起作用,这是一个包装,当回调或promise不可用时,我将其用作备份,并且需要使用timeout
功能进行后备:
// @param (callback): function to be run when done
// @param (delay): integer in milliseconds
// @param (id): string value of a unique event id
delayedEvent: (function () {
var timers = {},
defEvent = cfg.events;
return function (callback, delay, id) {
delay = delay || 1000;
id = id || 'some id';
if (timers[id]) {
clearTimeout(timers[id]);
}
timers[id] = setTimeout(callback, delay);
};
})(),
您可以像这样使用它:
responseCode = cloudLookupCall();
delayedEvent(function(){
if (responseCode === "Deny"){
// continue here
}
}, 1000, 'cloudlookup');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.