Skip to content

makeAbortApi

makeAbortApi is a function that creates an abort signal and its associated abort function.

Import

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

Usage

function makeAbortApi(signal?: AbortSignal): [
signal: AbortSignal,
abort: (reason?: unknown) => void,
];

Arguments

signal

The abort signal to associate.

Return Value

Returns an array containing the following, in order:

signal

An abort signal. It is not aborted initially.

abort

Dispatches an "abort" event to the abort signal. Optionally, it accepts a single argument reason, which can be used to convey the reason for the abort via the "abort" event.

Examples

The following example creates an Abort API without any arguments:

import { makeAbortApi } from "@tai-kun/surrealdb/utils";
const [signal, abort] = makeAbortApi();
abort();

The above example is almost equivalent to new AbortController(). The difference is that makeAbortApi returns an array instead of an object.

The following example creates an Abort API specifying an abort signal to associate:

import { makeAbortApi } from "@tai-kun/surrealdb/utils";
const controller = new AbortController();
controller.signal.addEventListener("abort", function() {
console.log("controller.signal", this.reason);
});
const [signal] = makeAbortApi(controller.signal);
signal.addEventListener("abort", function() {
console.log("signal", this.reason);
});
controller.abort("test");

Output:

controller.signal test
signal test

Abort events propagate from the Abort API to the associated abort signal:

import { makeAbortApi } from "@tai-kun/surrealdb/utils";
const controller = new AbortController();
controller.signal.addEventListener("abort", function() {
console.log("controller.signal", this.reason);
});
const [signal, abort] = makeAbortApi(controller.signal);
signal.addEventListener("abort", function() {
console.log("signal", this.reason);
});
abort("test");

Output:

controller.signal test
signal test