# Process Worker Executor

通过将进程和线程的调度封装为普通方法的调用方式简化了异步调用的复杂性。

## 功能

1. 使用 Async/Await 封装了 Nodejs 进程、线程调用
2. 通过简单的异步方法屏蔽了 IPC 通信细节
3. 使用代理的方式将同步方法代理为异步调用

## 注意

默认情况下代理的方法需要在方法本身的参数列表外的下一个明确指定使用异步

```js
// math add 方法定义的时候有两个参数，那么代理以后第三个参数指定是否异步执行
function add(a, b) {
    return a + b
}
// 禁用异步执行
const sum = await math.add(1, 2)
// 禁用异步执行
const sum = await math.add(1, 2, false)

// 启用异步执行
const sum = await math.add(1, 2, true) // 明确指定启用异步
```

## 用法

### 任务运行于独立进程

需要异步执行的脚本, 普通脚本即可

math.js

```js
async function add(x, y) {
    return x + y
}

async function sub(x, y, cb) {
    cb()
    return x - y
}

module.exports = {
    add,
    sub
}
```

调用方式

```js
const { requireScript } = require('process-worker-executor')

const mathPath = join(__dirname, 'math.js')
const math = await requireScript(mathPath, 'Process', {
    ttl: 60 * 1000,
    metedata: {
        // 其他需要传递给 Math 中函数使用的附加参数
        // 在 math.js 中使用 this._metedata 访问元数据对象
        // ...
    }
})
// 异步包装器会为代理的方法额外添加一个参数指定是否使用异步执行
// 此功能主要是为了方便用户动态指定其是否异步执行
// 方法支持传递函数作为其参数

// 主线程执行
const sum = await math.add(1, 2)
// 子线程/进程执行
const sum = await math.add(1, 2, true)
// 包含函数类型的参数
const sum = await math.sub(
    1,
    2,
    () => {
        // 函数可作为直接参数传递
        // 注意: 对象作为参数的时候, 对象中包含的方法不会传递
        // 具体支持的参数类型请查看[参数类型]
        // 函数类型参数通过消息传递调用, 此函数在主线程调用, 形参来自于子线程/进程的传参
        console.log('函数作为参数传递')
    },
    true
)
```

## 参数类型

1. 原始数据类型 Number, String, Boolean, null, 和 undefined
2. 普通的 JavaScript 对象和数组
3. Node 中的 Buffer 类型。
4. ArrayBuffer 和 Typed Array
5. Structured Cloneable types: 这指的是可以被结构化克隆的对象, 包括 Date、Map、Set 以及包含这些对象的数组和对象。
6. Process 和 Worker 模式下支持的参数类型略有不同
7. 具体参数请参考 process.send 和 worker.postMessage 方法参数
