[英]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.