Node.js - problems with async/await in a setInterval()

Asked

Viewed 112 times

-1

I am developing a bot to monitor an application. The function areaDocenteMonitor.start() makes only one request and returns the status. If the status is different from 200 an email is triggered with the error.

The function is executed at a given time using the setInterval().

Turns out he’s not respecting the await of the function that triggers the email and is trampling.

function start(time) {
  setInterval(async () => {
    const { status, statusText } = await areaDocenteMonitor.start();

    console.log(status, statusText);
    console.log(`${new Date()}\n`);

    if (status !== 200) {
      await mail.sendMail(
        template({
          title: 'Perda de conexão Área Docente',
          err: `${status} - ${statusText}`,
        })
      );
    }
  }, time);
}

Here is an example of the log:

502 Bad Gateway
Tue Mar 24 2020 19:37:43 GMT-0300 (GMT-03:00)

502 Bad Gateway
Tue Mar 24 2020 19:37:43 GMT-0300 (GMT-03:00)

502 Bad Gateway
Tue Mar 24 2020 19:37:44 GMT-0300 (GMT-03:00)

502 Bad Gateway
Tue Mar 24 2020 19:37:46 GMT-0300 (GMT-03:00)

Message sent: <[email protected]>
502 Bad Gateway
Tue Mar 24 2020 19:37:47 GMT-0300 (GMT-03:00)

Message sent: <[email protected]>
502 Bad Gateway
Tue Mar 24 2020 19:37:47 GMT-0300 (GMT-03:00)

Message sent: <[email protected]>
Message sent: <[email protected]>
502 Bad Gateway
Tue Mar 24 2020 19:37:48 GMT-0300 (GMT-03:00)

I wanted him to call the areaDocenteMonitor.start() only after he had completed the email shooting.

Can anyone give me a light? Or if there is another way to do it?

  • What time is being sent to setInterval?

1 answer

0

Hello, I made an example I hope to help you, assimilate your function in this same way that will probably solve your problem

const express = require('express')
const app = express()
 
app.get('/teste', function (req, res) {
  console.log('entrou na rota')
  //Função exemplo
  function areaDocenteMonitor(){
		console.log('<<<<< 1- areaDocenteMonitor >>>>>');
		return '500';
  }
  //Email exemplo
  function mail(){
	console.log('2 - Enviando email >>>>> \n');
  
  }
  
  function start(time) {
  setInterval(async() => {
    const x = await areaDocenteMonitor();

    console.log(x,`${new Date()}\n`);
   
    if (x !== '200') {
       const y = await mail();
    }
  }, time);
}

start(2000);

});
 
app.listen(3000, function (){
	console.log('Server Rodando')
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.