1
Such as
progress. That is, a promise is either fulfilled or rejected, never “50% done.” Some
promise libraries
add the very useful ability to report on progress, and it is possible
that functionality will arrive in JavaScript promises in the future, but for now, we
must make do without it. Which segues nicely into….
Events
Events are another old idea that’s gained traction in JavaScript. The concept of events
is simple: an event emitter broadcasts events, and anyone who wishes to listen (or
“subscribe”) to those events may do so. How do you subscribe to an event? A callback,
of course. Creating your own event system is quite easy, but Node provides built-in
support for it. If you’re working in a browser, jQuery also provides an
. To improve
countdown
, we’ll use Node’s
EventEmitter
. While it’s possible to
use
EventEmitter
with a function like
countdown
, it’s designed to be used with a
class. So we’ll make our
countdown
function into a
Countdown
class instead:
const
EventEmitter
=
require
(
'events'
).
EventEmitter
;
class
Countdown
extends
EventEmitter
{
constructor
(
seconds
,
superstitious
) {
super
();
this
.
seconds
=
seconds
;
this
.
superstitious
=
!!
superstitious
;
}
go
() {
const
countdown
=
this
;
return
new
Promise
(
function
(
resolve
,
reject
) {
for
(
let
i
=
countdown
.
seconds
;
i
>=
0
;
i
--
) {
setTimeout
(
function
() {
if
(
countdown
.
superstitious
&&
i
===
13
)
return
reject
(
new
Error
(
"DEFINITELY NOT COUNTING THAT"
));
countdown
.
emit
(
'tick'
,
i
);
if
(
i
===
0
)
resolve
();
}, (
countdown
.
seconds
-
i
)
*
1000
);
}
});
}
}
The
Countdown
class extends
EventEmitter
, which enables it to emit events. The
go
method is what actually starts the countdown and returns a promise. Note that inside
the
go
method, the first thing we do is assign
this
to
countdown
. That’s because we
need to use the value of
this
to get the length of the countdown, and whether or not
the countdown is superstitious inside the callbacks. Remember that
this
is a special
208 | Chapter 14: Asynchronous Programming