Search code examples
mysqlnode.jsexpressmysqljs

NodeJS-Express request with MySQL functions inside needs async?


I'm new to MySQL(JS) in NodeJS, I always used MongoDB. So now I'm confused because while all request with Mongoose functions inside in tutorials had async await, MySQL tutorials of the same thing is not, about 50% have and 50% not. Sometimes literally just the 2 word: async await is the difference of the tutorials.

Example very simple code:

//Simple
router.get('/all', (req, res) => {
    //something here...
    db.query('SELECT * FROM table;', (error, result) => {
        if (error) { 
          res.json(error);
        } else {
          res.json(result.Array());
        }
    });
    //something here...
});

//Async Await
router.get('/all', async(req, res) => {
    //something here...
    await db.query('SELECT * FROM table;', (error, result) => {
        if (error) { 
          res.json(error);
        } else {
          res.json(result.Array());
        }
    });
    //something here...
});

So what is the correct? Or it is really "optional" in MySQLJS?


Solution

  • So I'm using mysqljs for a while and i went without async. I also asked some people who use it and they all said async not needed here. The tutorials with async probably took async because of mongodb where async is needed and since mysql is a database too they think they should use it here too.

    TLDR: Async not needed for mysqljs.