0

In my javascript script I'm forced to use the EventEmitter and split the problem into two functions.

Is there any way to make a synchronos event listener? So the script would wait until the the event was triggered.

const EventEmitter = require('events');
var emitter = new EventEmmitter();

function bar(arg) {
  //calculations and stuff
  emitter.emit('done', result);
}

function foo(arg) {
  bar(arg);
  emitter.on('done', (result) => {
    return result; //this return statement doesn't work for foo()
  });

  //the code here should be processed after the event above was triggered.
  //here should be a return statement for the result 

}

console.log(foo("something")); //or process the result otherwise
1cedsoda
  • 623
  • 4
  • 16
  • Why not put the code instide the 'done' callback? – Rolando Cruz May 22 '18 at 13:54
  • Because I can't put a return statement for foo() into an anonymous function. – 1cedsoda May 22 '18 at 13:56
  • 1
    Possible duplicate of [Returning a value of a function with Promise object](https://stackoverflow.com/questions/42725584/returning-a-value-of-a-function-with-promise-object) – eisbehr May 22 '18 at 14:08
  • 2
    Please explain, in detail, what you are trying to do and what your problem set is. I think that you are misunderstanding the intention behind the event loop and event listeners in general. – zero298 May 22 '18 at 14:10
  • @zero298 event listeners and event loop have nothing in common, `emit()` synchronously calls listeners. But I agree that the code is not idiomatic and it would be better to use callback-based approach – Andrii Maletskyi May 22 '18 at 14:13
  • bar() is a function to calculate a xxHash of a file asynchronously by using fs.createReadStream(). The hash is getting emitted. foo() compares the hash with a previous calculated hash und returns if the content of the file has changed. – 1cedsoda May 22 '18 at 14:17
  • @phyyyl well, then you just cannot. It is impossible to wait synchronously for the result of asynchronous function. You should either rewrite `foo()` to be asynchronous or `bar()` to be synchronous – Andrii Maletskyi May 22 '18 at 14:25

0 Answers0