-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
waitForBatch.ts
75 lines (70 loc) · 2.2 KB
/
waitForBatch.ts
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import { hasBatchIndex } from '@prisma/engine-core'
/**
* Waits for result of batch $transaction and picks the best possible error to report if any
* of the request fails. Best error is determined as follows:
*
* - if engine have reported an error without batch request index, then the batch is immediately rejected
* with this error without waiting for other promises
* - if engine have reported and index of failed request in the batch and that index matches the position of the
* particular request in the batch, batch is rejected with that error
* - if batch request index is reported and it does not match current request position, wait for other requests. If no indices
* match request positions, reject with the earliest error in the batch
*
* @param promises
* @returns
*/
export function waitForBatch<T extends PromiseLike<unknown>[]>(
promises: T,
): Promise<{ [K in keyof T]: Awaited<T[K]> }> {
if (promises.length === 0) {
return Promise.resolve([] as { [K in keyof T]: Awaited<T[K]> })
}
return new Promise((resolve, reject) => {
const successfulResults = new Array(promises.length) as { [K in keyof T]: Awaited<T[K]> }
let bestError: unknown = null
let done = false
let settledPromisesCount = 0
const settleOnePromise = () => {
if (done) {
return
}
settledPromisesCount++
if (settledPromisesCount === promises.length) {
done = true
if (bestError) {
reject(bestError)
} else {
resolve(successfulResults)
}
}
}
const immediatelyReject = (error: unknown) => {
if (!done) {
done = true
reject(error)
}
}
for (let i = 0; i < promises.length; i++) {
promises[i].then(
(result) => {
successfulResults[i] = result
settleOnePromise()
},
(error) => {
if (!hasBatchIndex(error)) {
immediatelyReject(error)
return
}
if (error.batchRequestIdx === i) {
immediatelyReject(error)
} else {
if (!bestError) {
bestError = error
}
settleOnePromise()
}
},
)
}
})
}