简体   繁体   中英

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

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

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM