Skip to content
Advertisement

How should I call this node.js function?

I’m following a Node.js tutorial, it gave me the following code to start:


process.stdout.write("I'm thinking of a number from 1 through 10. What do you think it is? n(Write "quit" to give up.)nnIs the number ... ");

let playGame = (userInput) => {
  let input = userInput.toString().trim();
    testNumber(input);
};

It asked me to finish the app, so I did this, and it worked:

process.stdin.on('data', (userInput) => {
  let input = userInput.toString()
  playGame(input)
  //console.log(input)
});

However when I clicked the “check your work” button, it said that I did it wrong. The correct answer ended up being this:

process.stdin.on('data', (userInput) => {
  let input = userInput.toString()
  //console.log(input)
});

process.stdin.on('data', playGame)

I have a couple of questions about this. 1. Why does the playGame method need to be called in a listener rather than just explicitly calling it in the same method that grabs the user’s data? 2. Why doesn’t this example create a race condition? Don’t events emitted with the ‘data’ name fire at the same time? Sorry if these are basic questions, just trying to understand what I’m learning. Thanks in advance for any insight.

Advertisement

Answer

What were the exact instructions in your tutorial?

process.stdin is a Stream, which in turn is an EventEmitter. The data event callbacks will be executed when the emitter emits the data event. Here is what the documentation says regarding emit():

Synchronously calls each of the listeners registered for the event named eventName, in the order they were registered, passing the supplied arguments to each.

So as far as I understand, the two solutions are functionnally equivalent – more specifically, splitting the code in two separate callbacks will not allow the event loop to execute any other code in between. Note that you are still doing a redundant string conversion with your solution.

Also, there is no race condition since, again, the callbacks will be executed one after the other in the order in which they are registered. There actually is one single execution thread in the javascript execution model – so essentially only a single piece of javascript code can execute at any given point in time.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement