Question

I’m trying to create a worker that does the following simultaneously:

  1. Sends an XMLHTTPRequest to a server to perform a task (which may take a long time)

  2. Sends an XML HTTP Request Message every X seconds to get an update on the process until the process (1) is complete.

What i have so far is below. But it doesnt poll. The first part is successfully executed. The second bit runs just once. Does anyone know what i'm doing wrong?

onmessage = function (e) {

e.data.params.task = "runTask"; // The server understands this. This performs(1)

// Sends an asynchronous request to perform (1)
var xhr = new XMLHttpRequest();
xhr.open('POST', e.data.url, false);
xhr.setRequestHeader("Content-type", "application/json");
xhr.send(JSON.stringify(e.data.params));

// initialise polling
var interval = 500;

// Poll until (1) is complete
(function poll(){
  if (xhr.readyState != 4){ // while (1) is yet to be completed..


    e.data.params.task = "getProgress";

    // Send another request to the server to get an update on the first process
    var pollxhr = new XMLHttpRequest();
    pollxhr.open('POST', e.data.url, true);
    pollxhr.setRequestHeader("Content-type", "application/json");
    pollxhr.timeout = interval;
    pollxhr.ontimeout = poll; // This should cause the process to poll

    pollxhr.onreadystatechange = function(){    
      e.data.progress = pollxhr.responseText;               
      postMessage(e.data);
    };

    pollxhr.send(JSON.stringify(e.data.params));

}else{
            e.data = xhr.responseText;
            postMessage(e.data);
            }       
            })();


};
Was it helpful?

Solution

The problem is with the first call

xhr.open('POST', e.data.url, false);
                             ^^^^^

Looking at the method you can see the third parameter is async

 open(DOMString method, DOMString url, optional boolean async, optional DOMString? user, optional DOMString? password);

By setting it to false, you are telling it to run synchronously, which means nothing else will happen until it the call is returned. That results in your polling code running after the first call is returned. Set it to run asynchronously and use the onreadystatechange to get when it is completed!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top