Exercise 3.3 - do we need to use nextTick() ? #31
Replies: 1 comment 1 reply
-
Hi Matt, thanks for reading the book. Yes you'll need a nextTick. That's
essentially the main takeaway from exercise 3.3 😉. Without it, the event
is emitted before the event emitter is even returned to the caller. The
event fires but it's not intercepted by any listener, because there are
none at the point.
…On Fri, Feb 26, 2021, 23:48 Matt Mayes ***@***.***> wrote:
Hi all - really enjoying this book!
I was wondering if in exercise 3.3 if we need to use the
process.nextTick() function to emit a 'tick' immediately after the
function is invoked? I notice that if I do not, and simply do something
like emitter.emit('tick', '3.3 update') that it never fires at all, even
if I remove the loop, and I'm trying to wrap my head around that... 🤔
import { EventEmitter } from 'events'
import { nextTick } from 'process'
function everyFifty(totalMil, cb) {
let startMil = 0
let ticks = 0
const emitter = new EventEmitter()
nextTick(() => emitter.emit('tick', '3.3 update')) // this will not fire w/o nextTick()
while (startMil <= totalMil) {
startMil += 50
if (startMil > totalMil) {
setTimeout(() => {
cb(ticks)
}, totalMil)
break
}
setTimeout(() => {
emitter.emit('tick', (ticks += 1))
}, startMil)
}
return emitter
}
function finished(total) {
console.log('completed total ticks:', total)
}
everyFifty(100, finished).on('tick', (ticks) => {
console.log('tick', ticks)
})
// -- output --
// tick 3.3 update
// tick 1
// tick 2
// completed total ticks: 2
—
You are receiving this because you are subscribed to this thread.
Reply to this email directly, view it on GitHub
<#31>,
or unsubscribe
<https://github.com/notifications/unsubscribe-auth/AAAZWZ4BXXOPBZNHGXWOAWTTBAXNJANCNFSM4YJJMPJQ>
.
|
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
stoptime
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Hi all - really enjoying this book!
I was wondering if in exercise 3.3 if we need to use the
process.nextTick()
function to emit a 'tick' immediately after the function is invoked? I notice that if I do not, and simply do something likeemitter.emit('tick', '3.3 update')
that it never fires at all, even if I remove the loop, and I'm trying to wrap my head around that... 🤔Beta Was this translation helpful? Give feedback.
All reactions