File size: 2,276 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
76
77
78
79
80
81
82
import { InvariantError } from '../../shared/lib/invariant-error'
import { AwaiterMulti, AwaiterOnce } from './awaiter'

describe('AwaiterOnce/AwaiterMulti', () => {
  describe.each([
    { name: 'AwaiterMulti', impl: AwaiterMulti },
    { name: 'AwaiterOnce', impl: AwaiterOnce },
  ])('$name', ({ impl: AwaiterImpl }) => {
    it('awaits promises added by other promises', async () => {
      const awaiter = new AwaiterImpl()

      const MAX_DEPTH = 5
      const promises: TrackedPromise<unknown>[] = []

      const waitUntil = (promise: Promise<unknown>) => {
        promises.push(trackPromiseSettled(promise))
        awaiter.waitUntil(promise)
      }

      const makeNestedPromise = async () => {
        if (promises.length >= MAX_DEPTH) {
          return
        }
        await sleep(100)
        waitUntil(makeNestedPromise())
      }

      waitUntil(makeNestedPromise())

      await awaiter.awaiting()

      for (const promise of promises) {
        expect(promise.isSettled).toBe(true)
      }
    })

    it('calls onError for rejected promises', async () => {
      const onError = jest.fn<void, [error: unknown]>()
      const awaiter = new AwaiterImpl({ onError })

      awaiter.waitUntil(Promise.reject('error 1'))
      awaiter.waitUntil(
        sleep(100).then(() => awaiter.waitUntil(Promise.reject('error 2')))
      )

      await awaiter.awaiting()

      expect(onError).toHaveBeenCalledWith('error 1')
      expect(onError).toHaveBeenCalledWith('error 2')
    })
  })
})

describe('AwaiterOnce', () => {
  it("does not allow calling waitUntil after it's been awaited", async () => {
    const awaiter = new AwaiterOnce()
    awaiter.waitUntil(Promise.resolve(1))
    await awaiter.awaiting()
    expect(() => awaiter.waitUntil(Promise.resolve(2))).toThrow(InvariantError)
  })
})

type TrackedPromise<T> = Promise<T> & { isSettled: boolean }

function trackPromiseSettled<T>(promise: Promise<T>): TrackedPromise<T> {
  const tracked = promise as TrackedPromise<T>
  tracked.isSettled = false
  tracked.then(
    () => {
      tracked.isSettled = true
    },
    () => {
      tracked.isSettled = true
    }
  )
  return tracked
}

function sleep(duration: number) {
  return new Promise<void>((resolve) => setTimeout(resolve, duration))
}