Function racePromises

  • Races multiple promises and returns the result of the first resolved promise along with its index-based identifier.

    Type Parameters

    • T

      The type of the promise results.

    Parameters

    • promises: Promise<T>[]

      An array of promises to race.

    Returns Promise<{
        result: Awaited<T>;
        winner: number;
    }>

    A promise that resolves to an object containing:

    • result: The result of the first resolved promise.
    • winner: An array index of the winning promise.
    const promises = [
    new Promise((resolve) => setTimeout(() => resolve('First'), 100)),
    new Promise((resolve) => setTimeout(() => resolve('Second'), 200))
    ];

    const result = await racePromises(promises);
    console.log(result); // { result: 'First', winner: 'Promise 0' }