简体   繁体   中英

Abort ajax call from web worker

I read some articles about Web Workers today and I tried something concerning ajax requests. In fact, I wanted to be able to store every ajax request my web worker has sent in order to abort them when you're clicking an element. However, the XHR object can't be cloned, so it can't be send via postMessage() worker method.

I tried to do it this way :

    let xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function () {
    let DONE = 4; // readyState 4 means the request is done.
    let OK = 200; // status 200 is a successful return.
    if (xhr.readyState === DONE) {
        if (xhr.status === OK) {
            handlePoints(JSON.parse(xhr.responseText));
        }
    }

    xhr.open('GET', '/api/widgets/burndownchart?widgetId='+ widgetId);
    xhr.send(null);
    self.postMessage([constants.EVENT_AJAX_CALL, xhr]);

But of course I've this error :

Uncaught DOMException: Failed to execute 'postMessage' on 'DedicatedWorkerGlobalScope': XMLHttpRequest object could not be cloned.

Do you have an idea about how doing this ? PS : sorry for my language's errors.

您将需要将对象保留在Web Worker中,并向Web Worker发送一条消息,要求它按需中止请求。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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