【发布时间】:2017-07-18 07:17:57
【问题描述】:
以下代码是我用于 http 长轮询的前端代码。在此,我期望代码 setTimeout(getChat, 0) 异步调用该方法。但是当 getChat 方法的 XHR 处于挂起状态时,不同方法的所有后续 XHR 也都进入挂起状态。
discussTask = function(taskId) {
taskIdChat = taskId
getChat() // initial call
}
var getChat = function() {
taskId = taskIdChat
payLoad = {
'task_id': taskIdChat,
'recent_message_id': recentMessageId
}
var xmlhttp = XHR('/chat/sync', 'POST', payLoad)
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState === 4) {
buildChat(JSON.parse(xmlhttp.responseText))
setTimeout(getChat, 0) // Async recursive call
}
}
}
var XHR = function(action, method, payLoad) {
var xmlhttp = new XMLHttpRequest()
xmlhttp.open(method, action, true)
xmlhttp.setRequestHeader('Content-Type', 'application/json;charset=UTF-8')
xmlhttp.send(JSON.stringify(payLoad))
return xmlhttp
}
【问题讨论】:
-
什么是“不同的方法”?为什么用相同的参数发出请求?
-
请将
;放在您的陈述末尾。依赖 ASI 是危险的。 -
设置TaskIdChat然后再将TaskId设置为与之前设置TaskIdChat相同的值有什么问题?
-
@Unlockedluca 第一个
taskId是一个局部变量,第二个是一个全局变量。但他从不使用全局taskId,所以不清楚他为什么这样做。 -
要实现服务端事件,最好使用SSE或者websockets,但是如果你想要更通用的解决方案,看这里hpbn.co/xmlhttprequest/#streaming-data-with-xhr
标签: javascript asynchronous long-polling