我知道如何访问单独线程的唯一方法是使用 Web Workers。
您可以为工作人员创建一个文件:
/////////////////////////////////////////// Main (main.js)
const worker = new Worker('worker.js')
// Set up a listener for messages from the worker
worker.onmessage = (message) => {
// This is where you receive your worker response
}
// Error handling
worker.onerror = console.error
// This message will be passed to the worker
worker.postMessage('hello worker')
/////////////////////////////////////////// Web workers (worker.js)
self.onmessage = (message) => {
// message.data is where your passed parameter is stored
const data = message.data
// Execute some code
// Send back a response to the main thread (main.js)
postMessage(data)
}
或者您实际上可以创建一个动态工作人员:
// main.js
// This function will be passed into the worker
function test(message) {
const data = message.data
// Response
postMessage(data)
}
// Dynamic creation of a worker
const bytes = new TextEncoder().encode(`self.onmessage = ${test.toString()}`)
const blob = new Blob([bytes], {type: 'application/javascript'})
const url = URL.createObjectURL(blob)
const worker = new Worker(url)
// Set up a listener for messages from the worker
worker.onmessage = (message) => {
// This is where you receive your worker response
}
// Error handling
worker.onerror = console.error
// This message will be passed to the worker
worker.postMessage('hello')
第三个变体是使用我自己的 npm 库
@a4tur/threads.js
API 易于使用。
import Threads from '@a4tur/threads.js'
// Creating new threads
const threads = new Threads(4)
// Task to execute on separated threads
function test(param) {
param = param ?? 0
// Note that passed message is directly accessible. So no `message.data`
// Execute some code
// Just a regular return to get the message
return param + 10
}
// @param task: Function to execute
// @param message?: Parameter value of the function
// Chainable
threads.push(test, 20).push(test, 10).push(test)
// Execution
// You will get all responses in the same order you pushed tasks
const result = await threads.execute()