ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
# Worker ### Worker Worker 实例,主线程中可通过 [wx.createWorker](/read/wechat-game-api/334.md) 接口获取,worker 线程中可通过全局变量 `worker` 获取。 #### 方法 ##### Worker.postMessage(Object message) 向主线程/Worker 线程发送的消息。 ##### Worker.terminate() 结束当前 worker 线程,仅限在主线程 worker 对象上调用。 ##### Worker.onMessage(function callback) 监听主线程/Worker 线程向当前线程发送的消息的事件。 #### 示例代码 运行以下代码需先进行基础配置,详细请查阅 [多线程](https://developers.weixin.qq.com/minigame/dev/tutorial/usability/worker.html) 文档了解基础知识和配置方法。 ``` <pre class="prettyprint"><ol class="linenums"><li class="l"><code class="pcalibre9 pcalibre8 pcalibre7"><span class="kwd">const</span><span class="pln"> worker </span><span class="pun">=</span><span class="pln"> wx</span><span class="pun">.</span><span class="pln">createWorker</span><span class="pun">(</span><span class="str">'workers/request/index.js'</span><span class="pun">)</span><span class="pln"> </span><span class="com">// 文件名指定 worker 的入口文件路径,绝对路径</span></code></li> <li class="l1"><code class="pcalibre9 pcalibre8 pcalibre7"></code></li> <li class="l"><code class="pcalibre9 pcalibre8 pcalibre7"><span class="pln">worker</span><span class="pun">.</span><span class="pln">onMessage</span><span class="pun">(</span><span class="hljs-params"><span class="kwd">function</span></span><span class="pln"> </span><span class="pun">(</span><span class="hljs-params"><span class="pln">res</span></span><span class="pun">)</span><span class="pln"> </span><span class="pun">{</span></code></li> <li class="l1"><code class="pcalibre9 pcalibre8 pcalibre7"><span class="pln"> console</span><span class="pun">.</span><span class="pln">log</span><span class="pun">(</span><span class="pln">res</span><span class="pun">)</span></code></li> <li class="l"><code class="pcalibre9 pcalibre8 pcalibre7"><span class="pun">})</span></code></li> <li class="l1"><code class="pcalibre9 pcalibre8 pcalibre7"></code></li> <li class="l"><code class="pcalibre9 pcalibre8 pcalibre7"><span class="pln">worker</span><span class="pun">.</span><span class="pln">postMessage</span><span class="pun">({</span></code></li> <li class="l1"><code class="pcalibre9 pcalibre8 pcalibre7"><span class="pln"> msg</span><span class="pun">:</span><span class="pln"> </span><span class="str">'hello worker'</span></code></li> <li class="l"><code class="pcalibre9 pcalibre8 pcalibre7"><span class="pun">})</span></code></li> <li class="l1"><code class="pcalibre9 pcalibre8 pcalibre7"></code></li> <li class="l"><code class="pcalibre9 pcalibre8 pcalibre7"><span class="pln">worker</span><span class="pun">.</span><span class="pln">terminate</span><span class="pun">()</span></code></li> </ol> ``` > 原文: <https://developers.weixin.qq.com/minigame/dev/api/worker/Worker.html>