即使文件路径无效,Web Worker 构造函数也不会失败 [英] web worker constructor does not fail even with invalid file path

查看:29
本文介绍了即使文件路径无效,Web Worker 构造函数也不会失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在与 webpack 3 捆绑的网络文件中有此代码:

let _worker = new Worker("x.js")_worker.addEventListener('message', (event) => {解决(event.data as any)});

无论我传递给构造函数的路径是什么,worker 创建总是成功的.这怎么可能?

解决方案

这怎么可能?

因为它是异步.您不希望您的主 JavaScript 线程闲置、阻塞、等待浏览器从服务器获取脚本文件.所以它是异步完成的.

如果您监听工作线程的 error 事件,您将收到使用无效路径创建的工作线程的事件.

规范中涵盖了规范 在标记为 调用 Worker(scriptURL) 构造函数时,用户代理必须运行以下步骤:" 的步骤列表中的 a> 未列出有关浏览器获取 URL 的任何信息.

最后一步是运行工人,开头是这样的:

<块引用>

  1. 创建一个单独的并行执行环境(即一个单独的线程或进程或等效结构),并在该上下文中运行其余步骤.

...

  1. 让 request 成为一个新的请求,其 url 为 url...

  2. 让响应成为获取请求的结果.

  3. 如果响应响应的状态是 ok 状态...

    否则,对于与 worker 全局范围关联的每个 Worker 或 SharedWorker 对象,将任务排队以在该对象上触发名为 error 的简单事件.中止这些步骤.

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?

解决方案

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.

这篇关于即使文件路径无效,Web Worker 构造函数也不会失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆