tencent cloud

Tencent Cloud Super App as a Service

文档Tencent Cloud Super App as a Service

Multi-Threaded Worker

Download
聚焦模式
字号
最后更新时间: 2025-11-28 09:48:45
本文档由 AI 翻译
Some async tasks can be run in a worker. At the end of run, the results are returned to the main thread of the Mini Program. The worker runs in a separate global context and thread, and cannot directly call the methods of the main thread.
Data transfer between the worker and the main thread is accomplished using Worker.postMessage() to send data and Worker.onMessage() to receive data. The data to be transferred is not directly shared but copied.

Procedures

Configure Worker Information

In app.json, you can configure the directory where Worker code is placed. The code in the directory is packaged into a file:
Configuration example:
{
"workers": "workers"
}
By configuring it in the above way, all the JS files under the workers directory will be packaged into one JS file and be part of the first package of the mini program.

Add Worker Code Files

Based on the configuration in Step 1, create the following two entry files:
workers/request/index.js
workers/request/utils.js
workers/response/index.js
After the files are added, the directory structure is shown as below:
├── app.js
├── app.json
├── project.config.json
└── workers
├── request
│ ├── index.js
│ └── utils.js
└── response
└── index.js

Write Worker Code

Write the worker response code in workers/request/index.js.
const utils = require('./utils')
// In the worker thread execution context, a worker object is globally exposed and can be directly called by worker.onMessage/postMessage.
worker.onMessage(function (res) {
console.log(res)
})

Initialize Worker in Main Thread

Initialize worker in app.js of the main thread.
const worker = wx.createWorker('workers/request/index.js') // The filename specifies the worker entry file path as an absolute path.

Main Thread Sends a Message to Worker

worker.postMessage({
msg: 'hello worker'
})

Notes

The maximum concurrency of worker is one. Use Worker.terminate() to terminate the current worker before creating the next one;
The code in the worker can only require files in the specified worker path. It cannot reference other paths;
The worker entry files are specified when calling wx.createWorker(). Developers can dynamically specify the worker entry files;
wx APIs are not supported in workers;
Workers cannot send messages to each other.


帮助和支持

本页内容是否解决了您的问题?

填写满意度调查问卷,共创更好文档体验。

文档反馈