async await not working with callback node (without promise)

余生长醉 提交于 2021-02-07 18:09:27

问题


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


回答1:


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.




回答2:


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




回答3:


Async only works with promises, to get things working you have to first convert all of your function to return promises. You can use Promise.promisify() to convert all callback style function to return a promise. Once it is done you can use these function with async-await.



来源:https://stackoverflow.com/questions/53707410/async-await-not-working-with-callback-node-without-promise

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!