Guest User

Untitled

a guest
Feb 25th, 2018
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.23 KB | None | 0 0
  1. // Learning JavaScript
  2. // chapter 14 : Asynchronous Programming
  3.  
  4. // Promise & Events
  5.  
  6. const EventEmitter = require('events').EventEmitter;
  7.  
  8. class Countdown extends EventEmitter {
  9. constructor(seconds, superstitious) {
  10. super();
  11. this.seconds = seconds;
  12. this.superstitious = !!superstitious;
  13. }
  14. go() {
  15. const countdown = this;
  16. const timeoutIds = [];
  17. return new Promise(function(resolve, reject) {
  18. for (let i = countdown.seconds; i >= 0; i--) {
  19. timeoutIds.push(
  20. setTimeout(function() {
  21. if (countdown.superstitious && i === 13) {
  22. timeoutIds.forEach(clearTimeout);
  23. return reject(new Error('Oh my god'));
  24. }
  25. countdown.emit('tick', i);
  26. if (i === 0) resolve();
  27. }, (countdown.seconds - i) * 1000)
  28. );
  29. }
  30. });
  31. }
  32. }
  33.  
  34. const c = new Countdown(14, true);
  35.  
  36. c.on('tick', function(i) {
  37. if (i > 0) console.log(i + '...');
  38. });
  39.  
  40. c
  41. .go()
  42. .then(function() {
  43. console.log('Go!');
  44. })
  45. .catch(function(err) {
  46. console.error(err.message);
  47. });
Add Comment
Please, Sign In to add comment