Skip to main content
Deno 2 is finally here 🎉️
Learn more
Module

x/ayonli_jsext/esm/promise/index.js>select

A JavaScript extension package for building strong and modern applications.
Latest
function select
import { select } from "https://deno.land/x/ayonli_jsext@v0.9.72/esm/promise/index.js";

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

// 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

// 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

An array of promises or functions that return promises.

optional
signal = [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.