goryef
goryef

Reputation: 1489

Executing multiple queries in Nodejs route

I have Node.js post route in which I am executing several queries in sequence with async/await.

router.post("/foo", async (req, res) => {
    const qr1 = "str1";
    await db.query(qr1); // Works fine
    const qr2 = "str2";
    await db.query(qr2); // Works fine
    const qr3 = "str3";
    await db.query(qr3, async (err, result) => {
        if (err) {
            console.log(err);
        }
        if (result.length > 0) {
            // Required data is received – That part works
            // do something and continue to step 4
        }
    });
    // step 4 – Never gets here
});

All queries which perform table manipulation i.e. delete, insert etc work fine. Once I get to a select query I receive the required data but i need to continue to the next step which doesn't happen. I know I can accomplish what I need by nesting step 4 within step 3, but I would like to know if there is a different way to do that.

Upvotes: 0

Views: 383

Answers (1)

Rami
Rami

Reputation: 530

The issue you have is that comment // step 4 is executed immediately whereas the async(err code is executed asynchronously when query 3 executes. Here is your code corrected to achieve your result:

router.post("/foo", async (req, res) => {
try {
  const qr1 = "str1";
  await db.query(qr1); // Works fine
  const qr2 = "str2";
  await db.query(qr2); // Works fine
  const qr3 = "str3";
  const q3Result = await db.query(qr3);
  console.log('step 4');
  // step 4 – Should work fine
}
catch(err) {
  console.log(err);
}

});

Upvotes: 1

Related Questions