问题
I have this code in a web file bundled with webpack 3:
let _worker = new Worker("x.js")
_worker.addEventListener('message', (event) => {
resolve(event.data as any)
});
The worker creation always succeeds, no matter what path I pass to the constructor. How is this possible?
回答1:
How is this possible?
Because it's asynchronous. You wouldn't want your main JavaScript thread to sit around, blocked, waiting for the browser to fetch the script file from the server. So it's done asynchronously.
If you listen for the worker's error
event, you'll receive it for a worker created using an invalid path.
This is covered in the spec in the list of steps labelled "When the Worker(scriptURL) constructor is invoked, the user agent must run the following steps:" which doesn't list anything about the browser fetching the URL.
The last step in that is run a worker, which starts like this:
- Create a separate parallel execution environment (i.e. a separate thread or process or equivalent construct), and run the rest of these steps in that context.
...
Let request be a new request whose url is url...
Let response be the result of fetching request.
If response response's status is an ok status...
Otherwise, then for each Worker or SharedWorker object associated with worker global scope, queue a task to fire a simple event named
error
at that object. Abort these steps.
来源:https://stackoverflow.com/questions/47599137/web-worker-constructor-does-not-fail-even-with-invalid-file-path