threadfake
TypeScript icon, indicating that this package has built-in type declarations

2.1.0 • Public • Published

threadFake

这是一个伪的多线程,其原理是通过队列来实现的。

声明

// 任务ID
type TaskId = string;

// 选项参数
interface Options {
  // true: 先进先出,  false: 先进后出 
  lifo: boolean;
  // 任务状态
  state: boolean;
  // 最大执行任务数
  maxCount: number;
  // 删除成功任务,状态为 true 时会在队列合集中删除 success 属性
  removeSuccess: boolean;
  // 队列任务 ID Task Id
  getTaskId?: () => TaskId;
}

// 队列合集
interface Queue {
  // 任务Id合集
  list: TaskId[];
  // 正在处理的任务Id合集
  handle: TaskId[];
  // 任务合集
  value: Map<TaskId, Quest>;
  // 错误任务Id合集
  error: Map<TaskId, Quest>;
  // 成功任务Id合集,当 removeSuccess 为 true 时失效
  success?: Map<TaskId, Quest>;
}

// 任务
interface Quest {
  // try捕捉到的错误信息
  error?: any;
  // 成功后,方法返回的信息
  success?: any;
}

属性方法

interface ThreadFake {
  // 正在处理任务数量
  count: number;

  // 添加任务,callback 方法可以在任务执行后获取任务信息
  plus(target: Function, callback?: (quest: Quest, state: boolean) => void): void;

  // 开始,执行任务
  start(): void;

  // 暂停,需要等待正在执行的任务完成
  stop(): Promise<void>;

  // 清空全部任务,需要等待正在执行的任务完成
  clear(): Promise<void>;

  // 清空错误任务合集
  removeError(): void;

  // 清空成功任务合集
  removeSuccess(): void;

  // 添加事件
  on(keys: string, func: Function): void;

  // 删除事件
  off(key: string, func: Function): void;

  // 添加事件,事件执行一次后会自动删除
  once(key: string, func: Function): void;

  // 清空事件
  clearListeners(): void;
}

事件

事件名 参数 声明
load 初始化完成
stop 任务暂停,需要等待正在执行的任务完成后响应
empty 任务队列为空并且没有任务执行
before [TaskId, Quest] 任务开始前
handler [TaskId, State, Quest] 任务完成后

示例

const { ThreadFake } = require('../dist/index.js');

const thread = new ThreadFake({ removeSuccess: false });

for (let i = 0; i < 200; i++) {
  thread.plus(() => {
    if (Math.floor(Math.random() * 100) % 2 === 0) {
      return i;
    } else {
      return new Promise((resolve, reject) => {
        try {
          setTimeout(() => {
            resolve(i);
          }, 1000);
        } catch (e) {
          reject(e);
        }
      });
    }
  }, (quest) => {
    console.log('result: %s', quest['success']);
  });
}

thread.once('empty', () => {
  thread.removeSuccess();
  console.log(thread.queue);
});

Readme

Keywords

Package Sidebar

Install

npm i threadfake

Weekly Downloads

0

Version

2.1.0

License

MIT

Unpacked Size

18.3 kB

Total Files

14

Last publish

Collaborators

  • funny002