Home > Mobile >  How to send mysql queries sequentially using express in Node.js
How to send mysql queries sequentially using express in Node.js

Time:06-15

I wrote the following code, where I have a post request that executes 2 queries and some other operations:

router.post('/', (req, res) => {
    dbController.query(
        "SELECT * FROM users WHERE username = myUserName",
        (err, result) => {
            console.log('<---- 1 ---->')
        }
    )
    // do something
    console.log('<---- 2 ---->')
    // do something
    dbController.query(
        "SELECT * FROM users WHERE username = myUserName",
        (err, result) => {
            console.log('<---- 3 ---->')
    })
    res.send('ok')
})

I want to execute all instructions inside the function sequentially, so instead of getting this output (which is the one I get after executing the code):

<---- 2 ---->
<---- 1 ---->
<---- 3 ---->

I wanna get this one:

<---- 1 ---->
<---- 2 ---->
<---- 3 ---->

Note that after adding the keyword async to the function and await to the queries, nothing changes

CodePudding user response:

You need to wrap your logic in a .then() Your code should look something like this:

router.post('/', (req, res) => {
    dbController.query(
        "SELECT * FROM users WHERE username = myUserName",
        (err, result) => {
            console.log('<---- 1 ---->')
        }
    ). then(async function(rows){
// do something
    console.log('<---- 2 ---->')
    // do something
})
dbController.query(
        "SELECT * FROM users WHERE username = myUserName",
        (err, result) => {
            console.log('<---- 3 ---->')
    })
    res.send('ok')
})

You might also need to wrap the second query in a .then()

CodePudding user response:

If you give dbController.query a callback function (err, result) => {...} as third parameter, it does not return a promise, but instead invokes the callback asynchronously. If you omit this parameter, dbController.query returns a promise that

  • either resolves to result
  • or rejects as err.

The two flavors are functionally equivalent, but without the callback function as parameter, you can use async and await.

  • Related