简体   繁体   中英

Using a Web Worker to offload work

A presentation shows the following code as an example of promisifying functionality.

The intention is for the code to offload the computation associated with the JSON to the Web Worker.

var worker = new Worker('asyncTask.js');

function work(json) {    
    return new Promise(function(resolve, reject) {
      function onMessage() {
        worker.removeEventListener('message', onMessage);
        resolve.apply(this, arguments)
      }

      worker.addEventListener('message', onMessage);
      worker.postMessage(json);
    });
}

Am I correct in saying that this code is susceptible to a race condition in that the message received by the onMessage callback might not be related to the "corresponding" postMessage ?

With the caveat that I'm no WebWorker expert, I think the answer completely depends on the nature of the worker code. Since the worker context is just as single-threaded as the normal context, if the worker code just grinds away on some computation after getting the message, and posts the answer back when it's done, then even if there are other requests pending they'll wait. If the worker may pause and wait for more messages, then something would have to be set up to relate responses to what was requested.

I have the idea that any sort of service library written to use web workers might end up looking a little like an Erlang system, with a front-end API for the browser context that manages the message passing to and from the worker. If worker communication is such that requests and responses need to be matched up, then that front-end library would be in charge of handling that (like, by wrapping the API parameters in objects with unique request identifiers or something).

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