Skip to content

@neosjs/web-worker ​

创建和使用 Web Worker 有时会很麻烦:要单独维护 worker 脚本文件、处理双向消息通信。@neosjs/web-worker 的目的就是简化 Web Worker 的使用——直接把函数提交到其它线程执行,用 Promise 拿结果。

安装 ​

sh
pnpm add @neosjs/web-worker
sh
npm i @neosjs/web-worker
sh
yarn add @neosjs/web-worker

快速上手 ​

最简单的方式是 run:传入一个函数(以及可选的参数数组),函数会在其它线程执行,结果通过 Promise 返回:

ts
import webWorker from '@neosjs/web-worker'

webWorker.run(() => 'webWorker run 1: Function in other thread')
  .then(console.log)
  .catch(console.error)

webWorker.run(
  (arg1, arg2) => `webWorker run 2: ${arg1} ${arg2}`,
  ['Another', 'function in other thread']
)
  .then(console.log)
  .catch(console.error)

如果需要在同一个 Worker 中常驻多个任务,使用 create 注册一组动作,再通过消息名调用:

ts
import webWorker from '@neosjs/web-worker'

const actions = [
  {
    message: 'func1',
    action: () => 'Worker 1: Working on func1'
  },
  {
    message: 'func2',
    action: arg => `Worker 2: ${arg}`
  },
  {
    message: 'func3',
    action: arg => `Worker 3: ${arg}`
  },
  {
    message: 'func4',
    action: (arg = 'Working on func4') => `Worker 4: ${arg}`
  }
]

const worker = webWorker.create(actions)

worker.postMessage('func1')
  .then(console.log) // logs 'Worker 1: Working on func1'
  .catch(console.error)

// 未传参的动作参数为 undefined;可以调用时覆盖参数
worker.postMessage('func4', ['Overwrited argument'])
  .then(console.log) // logs 'Worker 4: Overwrited argument'
  .catch(console.error)

API ​

webWorker.run(func, [args]?) ​

在其它线程执行一次函数,返回 Promise。

参数说明类型
func要在 Worker 中执行的函数Function
args传给函数的参数数组(可选)any[]

webWorker.create([actions]?) ​

创建一个常驻 Worker 实例,actions 为 { message, action } 数组:

ts
const worker = webWorker.create([
  {
    message: 'func1',
    action: () => 'Working on func1'
  }
])

<worker>.postMessage(message, [args]?) ​

调用已注册的动作,返回 Promise。message 为动作名,args 可覆盖注册时的默认参数。

<worker>.postAllMessage([...messages]?) ​

依次调用多个(或全部)动作,结果按顺序以数组返回:

ts
worker.postAllMessage() // 调用全部动作
  .then(console.log)
  // logs ['Worker 1: Working on func1', 'Worker 2: undefined', ...]

worker.postAllMessage(['func1', 'func3']) // 只调用指定动作
  .then(console.log)

<worker>.register(action | [actions]) ​

为已创建的 Worker 追加注册动作:

ts
worker.register({
  message: 'func2',
  action: () => 'Working on func2'
})

// 注册多个操作
worker.register([
  {
    message: 'func3',
    action: () => 'Working on func3'
  },
  {
    message: 'func4',
    action: () => 'Working on func4'
  }
])

<worker>.unregister(message | [messages]) ​

取消注册动作:

ts
// 取消注册单个动作
worker.unregister('func2')

// 取消注册多个动作
worker.unregister(['func3', 'func1'])

关闭 Worker ​

将实例引用置空即可关闭 worker:

ts
let worker = webWorker.create(actions)
// ...
worker = null // close worker