-
-
Notifications
You must be signed in to change notification settings - Fork 185
Expand file tree
/
Copy pathPromiseRace.ts
More file actions
36 lines (33 loc) · 1.57 KB
/
PromiseRace.ts
File metadata and controls
36 lines (33 loc) · 1.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/race
import { PromiseState, __TS__Promise } from "./Promise";
// eslint-disable-next-line @typescript-eslint/promise-function-async
export function __TS__PromiseRace<T>(this: void, iterable: Iterable<T | PromiseLike<T>>): Promise<T> {
const pending: Array<PromiseLike<T>> = [];
for (const item of iterable) {
if (item instanceof __TS__Promise) {
if (item.state === PromiseState.Fulfilled) {
// If value is a fulfilled promise, return a resolved promise with its value
return Promise.resolve(item.value);
} else if (item.state === PromiseState.Rejected) {
// If value is a rejected promise, return rejected promise with its value
return Promise.reject(item.rejectionReason);
} else {
// If value is a pending promise, add it to the list of pending promises
pending.push(item);
}
} else {
// If value is not a promise, return a promise resolved with it as its value
return Promise.resolve(item);
}
}
// If not yet returned, wait for any pending promise to resolve or reject.
// If there are no pending promise, this promise will be pending forever as per specification.
return new Promise((resolve, reject) => {
for (const promise of pending) {
promise.then(
value => resolve(value),
reason => reject(reason)
);
}
});
}