Search code examples
javascriptasynchronouslong-polling

Async call not working in vanilla javascript


The following code is my frontend code for a http long poll. In this I am expecting the code setTimeout(getChat, 0) to call the method asynchronously. But when the getChat method's XHR is pending all following XHRs of different methods are also getting into pending state.

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
}

Solution

  • Found the issue. The Problem was not client side. I am using flask framework which by default will run in single threaded mode. So it was not serving the async requests from client side.