Guest User

Untitled

a guest
Feb 25th, 2018
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.03 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. return new Promise(function(resolve, reject) {
  17. for (let i = countdown.seconds; i >= 0; i--) {
  18. setTimeout(function() {
  19. if (countdown.superstitious && i === 13)
  20. return reject(new Error('Oh my god'));
  21. countdown.emit('tick', i);
  22. if (i === 0) resolve();
  23. }, (countdown.seconds - i) * 1000);
  24. }
  25. });
  26. }
  27. }
  28.  
  29. const c = new Countdown(5);
  30.  
  31. c.on('tick', function(i) {
  32. if (i > 0) console.log(i + '...');
  33. });
  34.  
  35. c
  36. .go()
  37. .then(function() {
  38. console.log('Go!');
  39. })
  40. .catch(function(err) {
  41. console.error(err.message);
  42. });
Add Comment
Please, Sign In to add comment