TaskQueue
TaskQueue
is a class for managing asynchronous tasks. It does not provide a mechanism for controlling concurrency; all task runners execute asynchronously.
Import
import { TaskQueue } from "@tai-kun/surrealdb/utils";
.constructor()
new TaskQueue();
Arguments
None.
Return Value
When called with new
, TaskQueue
returns a new instance of itself.
.count
instance property readonly
Represents the number of task runners currently added to the queue.
.add()
instance method
.add
adds a task runner to the queue.
add<T>( runner: (args: TaskRunnerArgs) => T | PromiseLike<T>, options?: TaskOptions,): StatefulPromise<T>;
Arguments
runner
The task runner function. The task runner will receive a TaskRunnerArgs
object as an argument, which includes an AbortSignal
(presumably signal
).
options
Options for the task runner. This allows passing an abort signal to the task runner.
Return Value
Returns a StatefulPromise
that resolves with the return value of the task runner.
Example
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()
instance method
.idle
is a function to wait until the queue is empty. Task runners are removed from the queue immediately after they complete, regardless of whether they resolve or reject. Therefore, an empty queue indicates that all task runners have finished executing.
idle(): StatefulPromise<void>;
Arguments
None.
Return Value
Returns a StatefulPromise
that resolves with void
.
Example
The following example waits for all added task runners to finish, regardless of whether they resolve or reject:
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);
Output:
20[ 'Hello' ]
In the above example, throw null
is not caught anywhere, and the script exits successfully. To detect errors in task runners, individual error handling is necessary.
.abort()
instance method
.abort
sends an abort signal to the signal
of all task runners.
abort(reason?: unknown): void;
Arguments
reason
The reason for the abortion.
Return Value
None.