aspirinemaga
aspirinemaga

Reputation: 3947

Sending a GET request on node.js process exit

I would like to send a telegram message by using a GET request before exiting the process.

I tried multiple combinations but none of them worked.

process.stdin.resume();

function onExit () {
  axios.get(`https://api.telegram.org/bot${config.telegram.BOT}/sendMessage`, {
    params: {
      chat_id: config.telegram.USER,
      parse_mode: 'markdown',
      text: 'message'
    }
  })
  console.log('Exiting...')
  process.exit()
}

['exit', 'SIGINT', 'SIGUSR1', 'SIGUSR2', 'uncaughtException', 'SIGTERM'].forEach((eventType) => {
  process.on(eventType, onExit.bind(null, eventType));
})

It ignores the axios request. What am I doing wrong here ? I know it should be synchronous only, but I'm not using any async/await here.

It shows fine the console logs "Exiting..." but that's all

Upvotes: 0

Views: 187

Answers (1)

Vasyl Moskalov
Vasyl Moskalov

Reputation: 4650

It happens because axios.get is async and returns a promise. Try this one:

function onExit () {
  axios.get(`https://api.telegram.org/bot${config.telegram.BOT}/sendMessage`, {
    params: {
      chat_id: config.telegram.USER,
      parse_mode: 'markdown',
      text: 'message'
    }
  })
  .then(_=>process.exit(),_=>process.exit());
  
  console.log('Exiting...')
}

Upvotes: 1

Related Questions