Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

151
Vistas
How to get data from MySQL and after 30 second fetch it again in Node.js?

I'm trying to do is fetching the data according to timestamp from DB once (call it origin) and wait for 30sec fetch it again with same query(call it recent) in Node.js.

Compare them if origin and recent is equal or not then do something depends on the result

Here is my code:

CREATE TABLE data(
  post_id VARCHAR(50) PRIMARY KEY,
  post_text TEXT ,
  post_img varchar(500),
  post_time TIMESTAMP,
);
const finalFn = async () => {
    let origin
    let recent

    origin = await getOg()

    recent = await setTimeout(function () {
        db.execute( // this one is same function with getOg()
            `SELECT * FROM data 
             WHERE post_time = (SELECT MAX(post_time) FROM data)`
            )
            .then(data => {
                return data[0][0]
            })
            .catch(err => console.log(err))
        console.log("I'm going to get some post")
    }, 5000) //5sec

    console.log('1', origin)
    console.log('2', recent)
    console.log(originPost === recent)  
}

finalFn()

i got 'oirgin' easily like:

{
  post_id: '12345',
  post_text: 'test',
  post_img: null,
  post_time: 2022-05-06...
}

the 'recent' should be the same right now, because no new data insert into DB yet.

but i got 'recent' like this:

Timeout {
  _idleTimeout: 5000,
  _idlePrev: [TimersList],
  _idleNext: [TimersList],
  _idleStart: 158,
  _onTimeout: [Function (anonymous)],
  _timerArgs: undefined,
  _repeat: null,
  _destroyed: false,
  [Symbol(refed)]: true,
  [Symbol(kHasPrimitive)]: false,
  [Symbol(asyncId)]: 29,
  [Symbol(triggerId)]: 0
}

im still learning asynchronous, so i think i must miss something in settimeout part...

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

setTimeout doesn't do async at all, and just returns a Timeout object, as you noticed. (awaiting something that's not a Promise will just return the object itself.)

You'll want something like this. The delay function is a common pattern to make setTimeout awaitable.

function delay(number) {
  return new Promise((resolve) => setTimeout(resolve, number));
}

async function getOg() {
  const res = await db.execute(`SELECT * FROM data WHERE post_time = (SELECT MAX(post_time) FROM data)`);
  return res[0][0];
}

const finalFn = async () => {
  const origin = await getOg();
  await delay(5000);
  const recent = await getOg();
  console.log("1", origin);
  console.log("2", recent);
};
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda