TaskQueue
TaskQueue
is a class for managing asynchronous tasks. It does not provide a mechanism to control concurrency; all task runners execute asynchronously.
Import
import { TaskQueue } from "@tai-kun/surrealdb/utils";
.constructor()
new TaskQueue();
Arguments
None.
Return Value
When called via new
, TaskQueue
returns its instance.
.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. The task runner’s arguments include TaskRunnerArgs
, which contains an abort signal (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 task runner’s return value.
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 that waits until the queue is empty. Task runners are removed from the queue immediately after completion (regardless of resolution or rejection). Therefore, an empty queue signifies that all task runners have finished execution.
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 unhandled, yet the script exits cleanly. To detect errors in task runners, individual error handling is necessary.
.abort()
instance method
.abort
is a function that sends an abort signal to the signal
of all task runners.
abort(reason?: unknown): void;
Arguments
reason
The reason for the abort.
Return Value
None.