1
\$\begingroup\$

I have a very basic XMLHttpRequest function that would be used with web workers.

I would like to know how I could improve it to handle possible errors better:

var ThreadedXhrRequest = function(url) {
    var worker = new Worker("xhrWorker.js");
    worker.postMessage([url]);
    worker.onmessage = function(d) {
        console.log(d.data)
    }
}

xhrWorker.js

onmessage = function(e) {
    var xhr = new XMLHttpRequest();
    xhr.open("GET", e[0], true);
    xhr.overrideMimeType("text/plain; charset=x-user-defined");
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4) {
            postMessage(xhr.responseText);
            close();
         }
    }
    xhr.send(null);
}
\$\endgroup\$
2
  • \$\begingroup\$ I don't understand why you are overwriting the worker.onmessage function rather than calling it. Without seeing what postMessage() does, it would appear that this code wouldn't actually do anything. Consider adding more context to your code in post. \$\endgroup\$
    – Mike Brant
    Commented Oct 25, 2016 at 13:34
  • \$\begingroup\$ worker.onmessage just log xhr.responseText to the console. It was based on this example: developer.mozilla.org/en-US/docs/Web/API/Worker/onmessage \$\endgroup\$ Commented Oct 25, 2016 at 16:41

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.