select.js 979 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. // jshint esnext: true, loopfunc: true
  2. var chan = require('..')
  3. var co = require('co')
  4. co(function *() {
  5. var count = 10
  6. , ch1
  7. , ch2
  8. while (count-- > 0) {
  9. // macke new channels
  10. ch1 = chan()
  11. ch2 = chan()
  12. // add a value on each channel after a random amout of time
  13. setTimeout(function () { ch1('ch1') }, Math.random() * 100 | 0)
  14. setTimeout(function () { ch2('ch2') }, Math.random() * 100 | 0)
  15. // will block until there is data on either ch1 or ch2,
  16. // and will return the channel with data
  17. // if data is on both channels, a channel will be selected at random
  18. switch (yield chan.select(ch1, ch2)) {
  19. // channel 1 received data
  20. case ch1:
  21. // retrieve the message from the channel
  22. console.log(yield ch1.selected)
  23. break
  24. // channel 2 received data
  25. case ch2:
  26. // retrieve the message from the channel
  27. console.log(yield ch2.selected)
  28. break
  29. }
  30. }
  31. })()