goryef
goryef

Reputation: 1489

Nodejs async/await for MySQL queries

I trying to execute 2 MySQL queries sequentially in Node.JS. MySQL queries work properly by itself. I would like to do it with async/await function to be sure record is inserted before it's updated. Here is the code:

router.post('/assign_new_item_id', async (req, res) => {
   .....
   try {
      let qr1= "INSERT INTO foo1 ........;"              
      await pool.query( qr1, (err) => {
         if (err) throw err;
      });
      let qr2= "UPDATE foo1 .....;"
      await pool.query( qr2, (err) => {
         if (err) throw err;
      });
   }catch(err){
     console.log(err)
} 

It seems that execution "hangs" within first await await block. What is the best way the ensure that both queries are executed consequently. Thanks in advance for any help.

Upvotes: 3

Views: 4668

Answers (1)

Aritra Chakraborty
Aritra Chakraborty

Reputation: 12542

To await you need a Promise, Not Callback. In your case you are not returning a promise to await.

router.post('/assign_new_item_id', async (req, res) => {
    // .....
    try {
        let qr1 = "INSERT INTO foo1 ........;"
        await new Promise((res, rej) => {
            pool.query(qr1, (err, row) => {
                if (err) return rej(err);
                res(row);
            });
        });
        let qr2 = "UPDATE foo1 .....;"
        await new Promise((res, rej) => {
            pool.query(qr2, (err, row) => {
                if (err) return rej(err);
                res(row);
            });
        });
    } catch (err) {
        console.log(err)
    }
});

Here I am promisifing the pool.query method and returning a promise.

Upvotes: 6

Related Questions