UNPKG

1.38 kBJavaScriptView Raw
1const RateLimitedQueue = require('./RateLimitedQueue')
2
3const delay = ms => new Promise(resolve => setTimeout(resolve, ms))
4
5describe('RateLimitedQueue', () => {
6 let pending = 0
7 function fn () {
8 pending++
9 return delay(15).then(() => pending--)
10 }
11
12 it('should run at most N promises at the same time', async () => {
13 const queue = new RateLimitedQueue(4)
14 const fn2 = queue.wrapPromiseFunction(fn)
15
16 const result = Promise.all([
17 fn2(), fn2(), fn2(), fn2(),
18 fn2(), fn2(), fn2(), fn2(),
19 fn2(), fn2()
20 ])
21
22 expect(pending).toBe(4)
23
24 await delay(10)
25 expect(pending).toBe(4)
26
27 await result
28 expect(pending).toBe(0)
29 })
30
31 it('should accept Infinity as limit', () => {
32 const queue = new RateLimitedQueue(Infinity)
33 const fn2 = queue.wrapPromiseFunction(fn)
34
35 const result = Promise.all([
36 fn2(), fn2(), fn2(), fn2(),
37 fn2(), fn2(), fn2(), fn2(),
38 fn2(), fn2()
39 ])
40
41 expect(pending).toBe(10)
42
43 return result.then(() => {
44 expect(pending).toBe(0)
45 })
46 })
47
48 it('should accept non-promise function in wrapPromiseFunction()', () => {
49 const queue = new RateLimitedQueue(1)
50 function syncFn () { return 1 }
51 const fn2 = queue.wrapPromiseFunction(syncFn)
52
53 return Promise.all([
54 fn2(), fn2(), fn2(), fn2(),
55 fn2(), fn2(), fn2(), fn2(),
56 fn2(), fn2()
57 ])
58 })
59})