0

I'm trying to understand how events in JavaScript work, and I have a VERY simple question. Say the following code:

const client = require('someLibrary')
let eventSource;
client.on('event', => {
   eventSource = client.someRandomThing
})
eventSource.on('event', => {
   // Anything here doesn't work.
})

I understand why the code won't work. The eventSource.on() is defined before the client.on('event'), but how would I create the eventSource handler AFTER eventSource changes from null (inside the client.on() section)?

This isn't a duplicate question, because I understand how to view a variable after it's been changed, but how would I directly call a handler?

jkdev
  • 11,360
  • 15
  • 54
  • 77
NeuronButter
  • 709
  • 1
  • 8
  • 24
  • 1
    so do you want to set a handler in a function; or fire an event in a function so that the handler is called? – YakovL Aug 07 '19 at 11:04
  • "The logic that depends on the asynchronous function execution should be started/called from inside this asynchronous function... because the result is available at that point." https://stackoverflow.com/a/23667087/3345375 ... – jkdev Aug 12 '19 at 21:43
  • ... so in your code, `eventSource.on('event', => { ... });` needs to be inside the function block `client.on('event', => { ... })` and it needs to be after `eventSource = client.someRandomThing;`. – jkdev Aug 12 '19 at 21:44

0 Answers0