Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
microsoft
GitHub Repository: microsoft/vscode
Path: blob/main/extensions/copilot/src/extension/inlineEdits/vscode-node/raceAndAll.ts
13399 views
1
/*---------------------------------------------------------------------------------------------
2
* Copyright (c) Microsoft Corporation. All rights reserved.
3
* Licensed under the MIT License. See License.txt in the project root for license information.
4
*--------------------------------------------------------------------------------------------*/
5
6
/**
7
* Runs multiple promises concurrently and provides two results:
8
* 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.
9
* 2. `all`: Resolves when all promises fulfill, with a tuple of all results.
10
* @param promises Tuple of promises to race
11
*/
12
export function raceAndAll<T extends readonly unknown[]>(
13
promises: {
14
[K in keyof T]: Promise<T[K]>;
15
},
16
errorHandler: (error: unknown) => void,
17
): {
18
first: Promise<{
19
[K in keyof T]: T[K] | undefined;
20
}>;
21
all: Promise<T>;
22
} {
23
let settled = false;
24
25
let rejectionCount = 0;
26
27
const first = new Promise<{
28
[K in keyof T]: T[K] | undefined;
29
}>((resolve, reject) => {
30
promises.forEach((promise, index) => {
31
promise.then(result => {
32
if (settled) {
33
return;
34
}
35
settled = true;
36
const output = Array(promises.length).fill(undefined) as unknown[];
37
output[index] = result;
38
resolve(output as {
39
[K in keyof T]: T[K] | undefined;
40
});
41
}, error => {
42
errorHandler(error);
43
rejectionCount++;
44
if (rejectionCount === promises.length) {
45
settled = true;
46
reject(new Error('All promises passed to raceAndAll were rejected'));
47
}
48
});
49
});
50
});
51
52
const all = Promise.all(promises) as Promise<T>;
53
54
return { first, all };
55
}
56
57