0

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.

4
  • The request/response cycle ends when you send back response. Are you sure inside the function you are not calling res.send() or something like that. Commented Oct 14, 2019 at 17:07
  • @khan I checked that. I don't believe I do. Commented Oct 14, 2019 at 17:13
  • What do you use to query the database - i.e. are you sure your lib's db.query returns a promise? Commented Oct 14, 2019 at 18:06
  • @StockOverflaw. Just a simple MySQL select query Commented Oct 14, 2019 at 18:12

1 Answer 1

1

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

});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.