为什么WebWorker在消息事件上多次触发?

时间:2014-10-22 10:44:41

标签: javascript ajax multithreading asynchronous web-worker

尝试从web-worker获取base64中的图像。一切都很好,除了工人多次回复.onmessage事件:

enter image description here

main.js部分:

var worker = new Worker( 'js/ww.js' );
worker.onmessage = function(e) {
    console.log( e );
};
worker.postMessage( { url: '/api/aerial?x=159&y=94&zoom=8&base64=true' } );

ww.js,WebWorker部分:

var self = this;

function makeRequest( url ) {
    var httpRequest = new XMLHttpRequest();

    if ( !httpRequest ) {
        console.error( 'Giving up. Cannot create an XMLHTTP instance.' );
        return false;
    }

    httpRequest.onreadystatechange = function() {
        var response = httpRequest.responseText;
        self.onMessage = postMessage( response );
    };

    httpRequest.open( 'GET', url, true );
    httpRequest.send();
}

self.addEventListener( 'message', function( event ) {
    makeRequest( event.data.url );
});

为什么会多次开火?

可能是因为使用了这种原生AJAX吗?

1 个答案:

答案 0 :(得分:0)

检查请求的正确状态和状态 在onreadystatechange - 处理程序中,您应该执行以下操作:

httpRequest.onreadystatechange = function() {
    if (httpRequest.readyState == 4 && httpRequest.status == 200) {
        var response = httpRequest.responseText;
        self.onMessage = postMessage( response );
    }
}