# Multithread Worker

Some asynchronous processing tasks can be placed in the Worker After the end of the run, and then return the results to the main Mini Program thread. Worker Running in a separate global context and thread, you cannot call the main thread's methods directly.

Worker And the data transfer between the main thread, both sides use Worker.postMessage() To send data,Worker.onMessage() The transmitted data is not shared directly, but is copied.

# Use Process

{% Minicode ('akaQknmy6ZY6') %}

# 1. To configure Worker information

in app.json Configurable in Worker Directory where the code is placed, all under the directory JS The code will eventually be packaged into a JS Documents:

Configuration Example:

{
  "workers": "workers"
}

In this way, workers All under the directory JS The file will be packaged as a JS File, and as part of the Mini Program's first package.

The size of the first package of the Mini Program is capped (currently 2M), in order to make worker The code does not occupy the first package volume, from the base library v2.27.3 Begin to support the will worker The code is packaged as a subcontract. (Developer tools need to be updated to the latest nightly Version)

worker The code is configured as a subcontract example:

{
  "workers": {
    "path": "workers",
    "isSubpackage": true  // true Indicates that the worker Packaged as a subcontract. default false。fill false Time is equivalent to { "workers": "workers" }
  }
}

# 2. Add to Worker Code file

According to the steps 1 Create the following two new entry files in the code directory

workers/request/index.js
workers/request/utils.js
workers/response/index.js

Added, the directory structure is as follows:

 app.js
 app.json
 project.config.json
 workers
     request
        index.js
        utils.js
     response
         index.js

# 3. write Worker code

in workers/request/index.js write Worker Response Code

const utils = Require('./utils')

// in Worker The thread execution context will globally expose a worker Object, calling directly the worker.onMessage/postMessage can then
worker.onMessage(function (res) {
  console.log(res)
})

# 4. Initialize in the main thread Worker

Code in the main thread app.js Initialization in Worker

const worker = wx.createWorker ('workers/request/index.js') // File name specified worker The entry file path, the absolute path

From the base library v2.27.3 Start. If worker Code is configured for sub-packageing, you need to first pass the wx.preDownloadSubpackage Interface download well worker Code, and then initialize Worker

var task = wx.preDownloadSubpackage({
   packageType: "workers", 
   success(res) {
      console.log("load worker success", res)
      var worker = wx.createWorker ("workers/request/index.js")   // create worker。 if worker Subcontract did not download the transfer createWorker  It will be wrong.
   },
   fail(res) {
      console.log("load worker fail", res)
   }
})

task.onProgressUpdate(res => {
  console.log(res.progress) // Available through onProgressUpdate  Interface monitor download progress
  console.log(res.totalBytesWritten )
  console.log(res.totalBytesExpectedToWrite)
})

# 5. The main thread to the Worker Send Message

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

worker For other interfaces to the object, see [Worker Interface Dxplaination]((wx.createWorker ))

# Note

  1. Worker The maximum number of concurrency is limited to 1 Please use before creating the next one. Worker.terminate() End the current Worker
  2. Worker The internal code can only Require Appoint Worker Files within the path, cannot refer to other paths
  3. Worker The entry file is provided by the [wx.createWorker ()]((wx.createWorker )) The developer can dynamically specify Worker Entry file
  4. Worker No support within wx Series of API
  5. Workers Sending messages is not supported between
  6. Worker The directory only supports placement JS Files, other types of static files need to be placed in the Worker Outside the Directory
  7. Base library v2.18.1 Start supporting the use within the plugin worker。Accordingly, the plug-in needs to use a worker beforeplugin.jsonInside configurationworkersCode path, a relative path to the plug-in code package root directory.