Path: blob/main/extensions/copilot/src/extension/inlineEdits/vscode-node/raceAndAll.ts
13399 views
/*---------------------------------------------------------------------------------------------1* Copyright (c) Microsoft Corporation. All rights reserved.2* Licensed under the MIT License. See License.txt in the project root for license information.3*--------------------------------------------------------------------------------------------*/45/**6* Runs multiple promises concurrently and provides two results:7* 1. `first`: Resolves as soon as the first promise fulfills, with a tuple where only that fulfilled value is set and the others are undefined.8* 2. `all`: Resolves when all promises fulfill, with a tuple of all results.9* @param promises Tuple of promises to race10*/11export function raceAndAll<T extends readonly unknown[]>(12promises: {13[K in keyof T]: Promise<T[K]>;14},15errorHandler: (error: unknown) => void,16): {17first: Promise<{18[K in keyof T]: T[K] | undefined;19}>;20all: Promise<T>;21} {22let settled = false;2324let rejectionCount = 0;2526const first = new Promise<{27[K in keyof T]: T[K] | undefined;28}>((resolve, reject) => {29promises.forEach((promise, index) => {30promise.then(result => {31if (settled) {32return;33}34settled = true;35const output = Array(promises.length).fill(undefined) as unknown[];36output[index] = result;37resolve(output as {38[K in keyof T]: T[K] | undefined;39});40}, error => {41errorHandler(error);42rejectionCount++;43if (rejectionCount === promises.length) {44settled = true;45reject(new Error('All promises passed to raceAndAll were rejected'));46}47});48});49});5051const all = Promise.all(promises) as Promise<T>;5253return { first, all };54}555657