Home > database >  How to get data from MySQL and after 30 second fetch it again in Node.js?
How to get data from MySQL and after 30 second fetch it again in Node.js?

Time:05-07

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...

CodePudding user response:

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);
};
  • Related