Categories
JavaScript Answers

How to prevent Node.js from exiting while waiting for a callback?

Spread the love

To prevent Node.js from exiting while waiting for a callback, we use the EventEmitter to wait for the event.

For instance, we write

const eventEmitter = new process.EventEmitter();

client.connect((err) => {
  eventEmitter.emit("myEvent", { something: "Bla" });
});

eventEmitter.on("myEvent", (myResult) => {
  process.stdout.write(JSON.stringify(myResult));
});

to create an EventEmitter objbect.

We emit the myEvent event with emit with { something: "Bla" } as the payload.

Then we listen for the myEvent event with on and get the payload from myResult.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *