web-worker-pools 为 worker 创建线程池
import Worker from './worker?worker';
import { webWorkerPools } from '@feige0629/web-worker-pools';
export interface ParamsType {
name:string;
}
export type ResultType = string;
const workerPools = new webWorkerPools<ParamsType, ResultType>({
"debug": true, //是否开启debug
"processName": 'testFunc', // 进程名称
"closeWorkerTime":60000, // 检查空闲 Worker 是否需要关闭(60秒)
"checkIdleInterval":60000 // 定时器间隔,用于检查空闲 Worker 是否需要关闭(60秒)
}, ()=>new Worker());
export const testFunc = async (params:ParamsType):Promise<ResultType> => {
return workerPools.workerManager(params, 'task1');
}
// 调用自动销毁
workerPools.autoCloseWorker(['task1']);// ['task1']为保留任务不超时销毁
import type { WorkerParams } from '@feige0629/web-worker-pools';
import type { ResultType, ParamsType } from './';
import { handleMessage, handleError } from '@feige0629/web-worker-pools';
function getResult(params:WorkerParams<ParamsType>): ResultType {
// 业务代码
return params.name; //测试返回name
}
// 监听消息
self.addEventListener("message", async (event: MessageEvent) => {
const params:WorkerParams<ParamsType> = event.data?.params;
handleMessage<ParamsType, ResultType>(event, ()=> getResult(params))
}, false)
// 错误提示
self.addEventListener("error", handleError, false);
import React, { useEffect, useState } from "react";
import { testFunc } from './index';
export function App(){
const [name, setName] = useState<string>('');
useEffect(()=>{
testFunc('飞哥')
.then((result:string)=>{
setName(result);
})
},[])
return <div>{name}</div>
}