Search code examples
javascriptexpressasync-awaitmysqljs

async await doesn't response in express.js with mysql.js


First I'm trying to insert data into the restaurant table.

After it finished (console log). It should call the second query (Insert audit). But it doesn't call that query and holds on the first function.

How do I fix this?

async function createRestaurant(req, res, next) {
    const restaurant = {
        name: req.body.name,
        description: req.body.description
    }

    const audits = {
        description: req.body.description
    }



    let query = "INSERT INTO restaurant SET ?";
    await connection.query(query, restaurant, (error, results) => {
        if (error) {
            console.log("Error at res")
            return true;
        } else {
            console.log("200 res")
            return true;

        }
    });

    let query2 = "INSERT INTO audits SET ?";
    await connection.query(query2, audits, (error, results) => {
        if (error) {
            console.log("Error at audit")

        } else {
            console.log("200 res")

        }
    });
}

module.exports = {
    createRestaurant: createRestaurant
}

Solution

  • You can't use async / await in every where. If you want use async / await it should be a promise. Since mysqljs is not a promised based library you can't use async / await here.