limitPromises.test.js 1001 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. const limitPromises = require('./limitPromises')
  2. describe('limitPromises', () => {
  3. let pending = 0
  4. function fn () {
  5. pending++
  6. return new Promise((resolve) => setTimeout(resolve, 10))
  7. .then(() => pending--)
  8. }
  9. it('should run at most N promises at the same time', () => {
  10. const limit = limitPromises(4)
  11. const fn2 = limit(fn)
  12. const result = Promise.all([
  13. fn2(), fn2(), fn2(), fn2(),
  14. fn2(), fn2(), fn2(), fn2(),
  15. fn2(), fn2()
  16. ])
  17. expect(pending).toBe(4)
  18. setTimeout(() => {
  19. expect(pending).toBe(4)
  20. }, 10)
  21. return result.then(() => {
  22. expect(pending).toBe(0)
  23. })
  24. })
  25. it('should accept Infinity as limit', () => {
  26. const limit = limitPromises(Infinity)
  27. const fn2 = limit(fn)
  28. const result = Promise.all([
  29. fn2(), fn2(), fn2(), fn2(),
  30. fn2(), fn2(), fn2(), fn2(),
  31. fn2(), fn2()
  32. ])
  33. expect(pending).toBe(10)
  34. return result.then(() => {
  35. expect(pending).toBe(0)
  36. })
  37. })
  38. })