我发布了一个名为sync-actions 的库,它允许异步进程在 javascript/typescript 中同步执行。特别是在 typescript 中,您可以以类型安全的方式调用定义的函数。它适用于您想要在您不希望(或不能)标记为异步的函数中执行异步进程的情况。
https://github.com/koyopro/sync-actions
它作为 npm 包发布,因此请使用 npm install 或类似的方式安装它。
npm install sync-actions
通过将返回promise对象的异步函数传递给definesyncworker(),您可以定义接口并使用launch()启动工作线程。假设定义工作程序的文件是与其他处理文件分开创建的。
// 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();
// 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 定义的函数。
// 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();
// 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 以类型安全方式使用的界面。
“accel record”简介:使用 active record 模式的 typescript orm ↩
为什么我们为新的 typescript orm 采用同步 api ↩
typescript 中的同步数据库访问技术↩
以上就是发布了一个用于 JS/TS 异步进程同步执行的库的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号