0

In essence I have a piece of code somewhat like:

function closeServerGracefully() {
  setTimeout(process.exit, 1000);
}

if (failingCondition) {
  logger.log('error', 'Fatal error exiting because failingCondition', closeServerGracefully);
}

logger.log('info', 'Everything is ok!');

(The last argument to logger.log is a callback function that gets called after the message is logged, I'm using winston)

However, if failingCondition does in fact become true my app outputs this:

Fatal error exiting because failingCondition
Everything is ok!

Then of course it crashes a few moments later because the problem wasn't caught properly.

How can I stop (or pause or kill) the execution of the "main" thread after that if statement is entered?

theonlygusti
  • 11,032
  • 11
  • 64
  • 119

2 Answers2

1

You can't stop main thread, you just can simulate "stop"

What's the equivalent of Java's Thread.sleep() in JavaScript?

You can try to do it without stopping:

if (failingCondition) {
  logger.log('error', 'Fatal error exiting because failingCondition', closeServerGracefully);
} else {
  logger.log('info', 'Everything is ok!');
}
Andrew Evt
  • 3,613
  • 1
  • 19
  • 35
-1

It is happening because the last log method is getting called before the timeout.

Things you can try:

You can try using a else there. So "Everything is ok!" will not logged if failingCondition is true.

If you are using this inside a method, you should try using a return; after logger.log() within the if block.

If you are trying to catch an exception, you should use a try/catch block.

Hope it helps!