You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

37 lines
991 B

4 years ago
  1. # inflight
  2. Add callbacks to requests in flight to avoid async duplication
  3. ## USAGE
  4. ```javascript
  5. var inflight = require('inflight')
  6. // some request that does some stuff
  7. function req(key, callback) {
  8. // key is any random string. like a url or filename or whatever.
  9. //
  10. // will return either a falsey value, indicating that the
  11. // request for this key is already in flight, or a new callback
  12. // which when called will call all callbacks passed to inflightk
  13. // with the same key
  14. callback = inflight(key, callback)
  15. // If we got a falsey value back, then there's already a req going
  16. if (!callback) return
  17. // this is where you'd fetch the url or whatever
  18. // callback is also once()-ified, so it can safely be assigned
  19. // to multiple events etc. First call wins.
  20. setTimeout(function() {
  21. callback(null, key)
  22. }, 100)
  23. }
  24. // only assigns a single setTimeout
  25. // when it dings, all cbs get called
  26. req('foo', cb1)
  27. req('foo', cb2)
  28. req('foo', cb3)
  29. req('foo', cb4)
  30. ```