import { select } from "https://deno.land/x/ayonli_jsext@v0.9.72/async.ts";
Runs multiple tasks concurrently and returns the result of the first task that completes. The rest of the tasks will be aborted.
Examples
Example 1
Example 1
// fetch example
import { select } from "@ayonli/jsext/async";
const res = await select([
signal => fetch("https://example.com", { signal }),
signal => fetch("https://example.org", { signal }),
fetch("https://example.net"), // This task cannot actually be aborted, but ignored
]);
console.log(res); // the response from the first completed fetch
Example 2
Example 2
// with parent signal
import { select } from "@ayonli/jsext/async";
const signal = AbortSignal.timeout(1000);
try {
const res = await select([
signal => fetch("https://example.com", { signal }),
signal => fetch("https://example.org", { signal }),
], signal);
} catch (err) {
if ((err as Error).name === "TimeoutError") {
console.error(err); // Error: signal timed out
} else {
throw err;
}
}
Parameters
tasks: (PromiseLike<T> | ((signal: AbortSignal) => PromiseLike<T>))[]
An array of promises or functions that return promises.
optional
signal: AbortSignal | undefined = [UNSUPPORTED]A parent abort signal, if provided and aborted before any task completes, the function will reject immediately with the abort reason and cancel all tasks.