inflight.js 842 B

12345678910111213141516171819202122232425262728293031323334353637
  1. 'use strict'
  2. module.exports = inflight
  3. let Bluebird
  4. try {
  5. Bluebird = require('bluebird')
  6. } catch (_) {
  7. Bluebird = Promise
  8. }
  9. const active = {}
  10. inflight.active = active
  11. function inflight (unique, doFly) {
  12. return Bluebird.all([unique, doFly]).then(function (args) {
  13. const unique = args[0]
  14. const doFly = args[1]
  15. if (Array.isArray(unique)) {
  16. return Bluebird.all(unique).then(function (uniqueArr) {
  17. return _inflight(uniqueArr.join(''), doFly)
  18. })
  19. } else {
  20. return _inflight(unique, doFly)
  21. }
  22. })
  23. function _inflight (unique, doFly) {
  24. if (!active[unique]) {
  25. active[unique] = (new Bluebird(function (resolve) {
  26. return resolve(doFly())
  27. }))
  28. active[unique].then(cleanup, cleanup)
  29. function cleanup() { delete active[unique] }
  30. }
  31. return active[unique]
  32. }
  33. }