rafiki_rafi
rafiki_rafi

Reputation: 1237

node.js eventEmitter setImmediate vs. async

I was reading up on the eventEmitter documentation and came across the section where they discuss async vs synchronous code. They have this example that showcases how to process an event asynchronously:

const myEmitter = new MyEmitter();
myEmitter.on('event', (a, b) => {
  setImmediate(() => {
    console.log('this happens asynchronously');
  });
});

My question is: would using the async keyword not achieve the same thing?

Wouldn't the following implementation also run asynchronously?

const myEmitter = new MyEmitter();
myEmitter.on('event', async () => {
  console.log('does this happens asynchronously????');
});

Upvotes: 0

Views: 409

Answers (1)

zero298
zero298

Reputation: 26909

It may help if you tell us why you think those would be the same.

The second function will execute on the event even though it is marked async (it will just return a promise that won't be used anywhere).

The first will also execute on the event but schedule its inner contents (the function that you pass to setImmediate) to be run when the event queue is empty.

async doesn't mean "do later" it just means "wrap my return in a promise automagically and allow me to use await in my function body".

Upvotes: 1

Related Questions