简体   繁体   English

使用XMLHTTPRequest从JavaScript工作者进行轮询

[英]Polling from a JavaScript worker using XMLHTTPRequest

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) 将XMLHTTPRequest发送到服务器以执行任务(这可能需要很长时间)

  2. Sends an XML HTTP Request Message every X seconds to get an update on the process until the process (1) is complete. 每隔X秒发送一次XML HTTP请求消息,以获取有关该进程的更新,直到进程(1)完成。

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);
            }       
            })();


};

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. 通过将其设置为false,您将告诉它同步运行,这意味着在返回调用之前不会发生任何其他事情。 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! 将其设置为异步运行,并使用onreadystatechange获取完成时间!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM