跳转到内容

TaskQueue

TaskQueue 是用于管理异步任务的类。它不提供控制并发性的方法,所有任务运行器都异步执行。

导入

import { TaskQueue } from "@tai-kun/surrealdb/utils";

.constructor()

new TaskQueue();

参数

无。

返回值

通过 new 调用时,TaskQueue 返回其实例。

.count 实例 属性 只读

表示当前添加到队列中的任务运行器的数量。

.add() 实例 方法

.add 用于将任务运行器添加到队列中。

add<T>(
runner: (args: TaskRunnerArgs) => T | PromiseLike<T>,
options?: TaskOptions,
): StatefulPromise<T>;

参数

runner

任务运行器。任务运行器的参数包含中止信号 signalTaskRunnerArgs

options

任务运行器的选项。可以传递此任务运行器的中止信号。

返回值

返回一个以任务运行器的返回值为决议结果的 StatefulPromise

例子

import { TaskQueue } from "@tai-kun/surrealdb/utils";
const queue = new TaskQueue();
const promise = queue.add(async ({ signal }) => {
const response = await fetch("https://example.com/", { signal });
return await response.text();
});
const text = await promise;
console.log(text);

.idle() 实例 方法

.idle 是一个用于等待队列为空的函数。任务运行器只有在完成(无论成功或失败)后才会从队列中移除。因此,队列为空意味着所有任务运行器的执行都已完成。

idle(): StatefulPromise<void>;

参数

无。

返回值

返回一个以 void 为决议结果的 StatefulPromise

例子

以下示例等待队列中添加的任务运行器完成(无论成功或失败):

import { TaskQueue } from "@tai-kun/surrealdb/utils";
const queue = new TaskQueue();
const results: string[] = [];
queue.add(async () => {
results.push("Hello");
});
queue.add(() => {
throw null;
});
console.log(queue.count);
await queue.idle();
console.log(queue.count);
console.log(results);

输出:

2
0
[ 'Hello' ]

在上面的例子中,throw null 没有被捕获,脚本正常结束。要注意到任务运行器的错误,需要单独进行错误处理。

.abort() 实例 方法

.abort 用于向所有任务运行器的 signal 发送中止事件的函数。

abort(reason?: unknown): void;

参数

reason

中止的原因。

返回值

无。