0

I'm quite new to Node JS, and I'm trying to build an API based on MySQL.
In one of my routers I'm trying to inject an insert query and based on it, get the new generated task id from mysql.
The problem is that the second query is not waiting for the response and sometimes I'm getting an error because taskId variable is undefined because it still didn't get the results from the first query.
the problematic variable that is not getting it's value correctly is taskId.
I'm attaching my code for your review, thanks for your help!
As requested: I'm attaching my required moudle as well:

const dotenv = require('dotenv');
const mysql = require('mysql');

dotenv.config();

var connection = mysql.createPool({
    host: process.env.DB_HOST,
    user: process.env.DB_USERNAME,
    password: process.env.DB_PASSWORD,
    database: process.env.DB_TABLE,
    port: process.env.DB_PORT
});

module.exports = connection;
router.post('/new', auth, async (req, res) => {
    const uid = req.body.uid;
    const taskName = req.body.taskName;
    const description = req.body.description;
    const createdDate = req.body.createdDate;
    const estimatedDate = req.body.estimatedDate;
    const status = req.body.status;
    let taskId = '';
    addTaskQuery = `INSERT INTO task (title,description,status) VALUES ('${taskName}','${description}','${status}')`;
    findTaskIdQuery = `SELECT id FROM task WHERE title = '${taskName}'`;
    try {
        // Injecting into task table
        await connection.query(addTaskQuery, (err, results) => {
            if(err) {
                console.log(err);
                return res.send(JSON.stringify({data: err}));
            }
        })
        // Getting the new inserted task id
        await connection.query(findTaskIdQuery, (err, results) => {
            if(err) {
                console.log(err);
                return res.send(JSON.stringify({data: err}));
            }
            taskId = JSON.stringify(results[0].id);
        })
        // Injecting into havetask table
        await connection.query(`INSERT INTO havetask (id,userId,taskId) VALUES (${taskId},${uid},${taskId})`, (err, results) => {
                    if(err) {
                        console.log(err);
                        return res.send(JSON.stringify({data: err}));
                    }
        })
    }
    catch(err) {
        console.log(err);
        return res.status(401).json({ msg: 'An error occured while tried to add task'});
    }
})
4
  • 2
    There are different ways to handle asynchronous results, like Promises or (err, result) callbacks. In general, even if an API supports both (returning a Promise, or accepting a callback) it is really unlikely that they will support both at the same time, so if you pass an (err, result) callback then the API most certainly won't return a Promise. Furthermore, you need to check if the mysql module you use is Promise based. Commented Jun 24, 2020 at 9:34
  • 1
    Please show us your require('mysql') or similar statement. Or, tell us which npm package you use for mysql. (Hint: it may not offer async / await operation.) Please edit your question. Commented Jun 24, 2020 at 10:00
  • @O.Jones I've edited and added my connector as well, thanks. Commented Jun 24, 2020 at 10:05
  • 1
    The mysql module does have a promise-based API, so you can't use await with it directly. Commented Jun 24, 2020 at 10:23

1 Answer 1

1

The mysql package you use does not support Promises (=== it doesn't do async / await). So your await statements don't wait, they just fall through.

You need to try a package that handles async / await. This one might do the trick.

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

1 Comment

Thats right, thanks a lot! I've changed the npm module to 'mysql2/promise' which solved my problem.

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.