小编Jay*_*Jay的帖子

Node.js 在 mysql 中使用 async/await

我一直在尝试在节点中将 async/await 与 MySQL 一起使用,但它每次都返回一个未定义的值。有什么原因吗?请在下面找到我的代码。

const mysql = require('promise-mysql');

    var connection;

    const dbConfig = {
        host: "hostname",
        database: "dbname",
        user: "username",
        password: "passwords"
    };

    async function getResult(){

        await mysql.createConnection(dbConfig).then(function(conn){

            connection = conn;
            var result = connection.query('select height from users where pin=1100');

            return result;

        }).then(function(rows){
            console.log(JSON.parse(JSON.stringify(rows[0].height)));
            connection.end();
            return rows[0].height;
        }).catch(function(error){
            if (connection && connection.end) connection.end();
            //logs out the error
            console.log(error);
        });
    }


    async function queryDb(){

        try{

         var height = await getResult(); 
        console.log(height);
         if(height){
            console.log(height)
         }

        }catch(err){
            console.log(err);
            console.log('Could not process request …
Run Code Online (Sandbox Code Playgroud)

javascript mysql node.js promise async-await

3
推荐指数
1
解决办法
1万
查看次数

标签 统计

async-await ×1

javascript ×1

mysql ×1

node.js ×1

promise ×1