web worker constructor does not fail even with invalid file path

妖精的绣舞 提交于 2019-12-24 11:39:08

问题


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:

  1. 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.

...

  1. Let request be a new request whose url is url...

  2. Let response be the result of fetching request.

  3. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!