【问题标题】:Async call not working in vanilla javascript [closed]异步调用在香草javascript中不起作用[关闭]
【发布时间】: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


【解决方案1】:

发现问题。问题不是客户端。我正在使用烧瓶框架,默认情况下将以单线程模式运行。所以它没有为来自客户端的异步请求提供服务。

【讨论】:

    猜你喜欢
    • 2021-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-09
    相关资源
    最近更新 更多