Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

async await not working with callback node (without promise)

hello guys i got confused why this not working here is my connection js file

    function getConnection(callback) {
        initPool()
        mysql_pool.getConnection((err, conn) => {
            if (err) {
                return callback(err);
            }
               return callback(err, conn);
        });
     }

    function query(queryString, callback) {

        getConnection((err, connection2) => {
            if (connection2 != undefined) {
                if (err) {
                    connection2.destroy();
                return  callback(createDataResponseObject(err, null))
                }
                connection2.query(queryString, function (err, rows) {
                    connection2.destroy();
                    if (!err) {
                        return callback(createDataResponseObject(err, rows))
                    }
                    else {
                        return callback(createDataResponseObject(err, null))
                    }
                });                   
            }

        });
    }
    function createDataResponseObject(error, results) {
        if (error) {
            logger.info(error);
        }
        return {
            error: error,
            results: results === undefined ? null : results === null ? null : results
        }
    }

now when i acquire this connection js in my router.js below is sample code

   var conn=require("./connection")
   router.post('/test',async function(res,req){
      var query ="select * from users"
      let x= await conn.query(result);
      console.log(x)        
   });      

in connection js file i haven't use promise then why async not working in router i.e it should still work because i m using callback can anyone tell me what i m missing or what i m doing wrong. when i tried it with return promise in connection.js file it working. i know async return promise

like image 564
bipin Avatar asked Jan 28 '23 01:01

bipin


2 Answers

You can only await a promise. conn.query doesn't return a promise. It has no return statement: It returns undefined.

You need to promisify your database functions.

like image 68
Quentin Avatar answered Jan 29 '23 21:01

Quentin


Async/await only works with promises, it’s a syntactic sugar on top of it. I.e. you can’t use the syntax with callbacks.

Check out this link: https://javascript.info/async-await

like image 40
busyfingers Avatar answered Jan 29 '23 20:01

busyfingers