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.

68 lines
1.4 KiB

7 years ago
  1. module.exports = function first(stuff, done) {
  2. if (!Array.isArray(stuff))
  3. throw new TypeError('arg must be an array of [ee, events...] arrays')
  4. var cleanups = []
  5. for (var i = 0; i < stuff.length; i++) {
  6. var arr = stuff[i]
  7. if (!Array.isArray(arr) || arr.length < 2)
  8. throw new TypeError('each array member must be [ee, events...]')
  9. var ee = arr[0]
  10. for (var j = 1; j < arr.length; j++) {
  11. var event = arr[j]
  12. var fn = listener(event, callback)
  13. // listen to the event
  14. ee.on(event, fn)
  15. // push this listener to the list of cleanups
  16. cleanups.push({
  17. ee: ee,
  18. event: event,
  19. fn: fn,
  20. })
  21. }
  22. }
  23. function callback() {
  24. cleanup()
  25. done.apply(null, arguments)
  26. }
  27. function cleanup() {
  28. var x
  29. for (var i = 0; i < cleanups.length; i++) {
  30. x = cleanups[i]
  31. x.ee.removeListener(x.event, x.fn)
  32. }
  33. }
  34. function thunk(fn) {
  35. done = fn
  36. }
  37. thunk.cancel = cleanup
  38. return thunk
  39. }
  40. function listener(event, done) {
  41. return function onevent(arg1) {
  42. var args = new Array(arguments.length)
  43. var ee = this
  44. var err = event === 'error'
  45. ? arg1
  46. : null
  47. // copy args to prevent arguments escaping scope
  48. for (var i = 0; i < args.length; i++) {
  49. args[i] = arguments[i]
  50. }
  51. done(err, ee, event, args)
  52. }
  53. }