发布了一个用于 JS/TS 异步进程同步执行的库

来源:undefined 2025-01-22 01:12:18 1040

我发布了一个名为sync-actions 的库,它允许异步进程在 javascript/typescript 中同步执行。特别是在 typescript 中,您可以以类型安全的方式调用定义的函数。它适用于您想要在您不希望(或不能)标记为异步的函数中执行异步进程的情况。

特征

利用 node.jsworker_threads 异步进程在子线程中执行,主线程同步等待其完成。 类型安全的函数调用 在 typescript 中,您可以利用已定义函数的类型信息。 作为原生 esm 发布 由于不支持 commonjs,它变得简单。

存储库

https://github.com/koyopro/sync-actions

用法

安装

它作为 npm 包发布,因此请使用 npm install 或类似的方式安装它。

1

npm install sync-actions

登录后复制

基本用法

通过将返回promise对象的异步函数传递给definesyncworker(),您可以定义接口并使用launch()启动工作线程。假设定义工作程序的文件是与其他处理文件分开创建的。

1

2

3

4

5

6

7

8

9

10

11

// worker.js

import { definesyncworker } from "sync-actions";

export const { actions, worker } = definesyncworker(import.meta.filename, {

ping: async () => {

// execute asynchronous process,

await new promise((resolve) => settimeout(resolve, 1000));

// return the result as a return value

return "pong";

}

}).launch();

登录后复制

1

2

3

4

5

6

7

// main.js

import { actions, worker } from "./worker.js";

// you can execute asynchronous functions synchronously

console.log(actions.ping()); // => "pong" is output after 1 second

worker.terminate();

登录后复制

类型安全的函数调用

在 typescript 中,您可以以类型安全的方式调用使用 definesyncworker 定义的函数。

1

2

3

4

5

6

7

8

9

// worker.ts

import { definesyncworker } from "sync-actions";

export const { actions, worker } = definesyncworker(import.meta.filename, {

// by specifying the types of arguments and return values, type-safe calls are possible

add: async (a: number, b: number): promise<number> => {

return a + b;

}

}).launch();

登录后复制

1

2

3

4

5

6

7

8

9

10

11

// main.ts

import { actions, worker } from "./worker.js";

// Type-safe call

actions.add(1, 2); // => 3 (number)

// @ts-expect-error

actions.add("1", 2);

// => Argument of type string is not assignable to parameter of type number

worker.terminate();

登录后复制

背景

到目前为止的内容与readme相同,所以我将描述它的创建背景。

我正在开发一个名为 accel record 的 orm。1与一般 orm 不同,accel record 旨在通过同步接口执行 db 访问。2 同步执行 db 访问的部分是通过在以child_process模块​​启动的子进程中执行异步进程来实现的。3我认为通过使用worker_threads而不是child_process,我可以减少运行时的开销。

accel record 在可用性方面也被设计为类似于 ruby on rails 的 active record,而我未来想要实现的目标之一就是创建一个像 carrierwave 这样的库。 carrierwave允许您在保存记录时将图像保存到外部存储服务(例如aws s3),而要使用accel record来实现这一点,需要同步执行图像上传等异步过程。我希望通过使用worker_threads而不是子进程可以更快地执行这个进程。

所以我曾经寻找过一个使用worker_threads同步执行异步进程的库。我发现了几个库,例如synckit和deasync,但它们都没有按照我的预期工作,所以我决定创建自己的库。从那时起,我就想制作一个可以通过 typescript 以类型安全方式使用的界面。

更多内部细节

直到以worker_threads启动的子线程中的异步进程完成为止,使用atomic.wait()阻塞主线程。 messagechannel 用于线程之间的通信。 synckit的源码对于这部分的实现非常有帮助。 当使用worker_threads启动worker时,需要将.ts文件转译为.js。对于这部分,我使用 esbuild。 启动 worker 时,我想将转译后的源代码作为字符串传递给 worker 执行,但它在我的环境中无法正常工作。这是我最挣扎的部分。最后,我将文件写在node_modules下,并将其路径传递给worker。这个方法被证明是最稳定的。

“accel record”简介:使用 active record 模式的 typescript orm ↩

为什么我们为新的 typescript orm 采用同步 api ↩

typescript 中的同步数据库访问技术↩

以上就是发布了一个用于 JS/TS 异步进程同步执行的库的详细内容,更多请关注php中文网其它相关文章!

最新文章