javascript/node.js不等待sql查询返回响应,然后继续执行代码

dy1byipe  于 2021-06-19  发布在  Mysql
关注(0)|答案(2)|浏览(339)

我有一个.js文件,它调用运行以下代码的外部.js文件:

const sql = require('../../node_modules/mysql');

module.exports =
    {
        connect_to_db: function (sql_query)
        {
            let con = sql.createConnection({
                host: "localhost",
                user: config.server_username,
                password: config.server_password,
                database: config.database_name
            });

            con.connect((err)=> {
                if (err){
                    console.log("Problem connecting to the DB!");
                    return;
                }
                console.log("Connected to the DB!");
            });

            con.query(sql_query, (err, result) => {
                if (err) throw err;
                console.log('Data received from the DB');
                console.log(result);
                return result;
            });

            con.end((err) => {});

        }
    };

运行方式如下:

const connect_to_DB = require('DB_Connection');     
let sql_query = "SELECT * FROM table";
                    database_results.push(connect_to_DB.connect_to_db(sql_query));

                    console.log(database_results);

但是,这会导致在sql查询返回结果(数据已删除)之前完成代码:

[ undefined ]

Connected to the DB!
Data received from the DB
[ RowDataPacket {
    mail_id: ,
    from: ,
    to: ',
    subject: ,
    message: ,
    date:,
    read_date:  } ]

Process finished with exit code 0

看起来结果的推力是未定义的,因为在它这样做的时候没有什么可以推力的。但是,我希望它等到查询的响应返回后再继续。
我在想一个承诺,也许,但不确定这是否会像:

const sql = require('../../node_modules/mysql');

module.exports =
    {
        connect_to_db: function (sql_query)
        {
            return new Promise((resolve, reject) => {
                (async () => {
                    let con = sql.createConnection({
                        host: "localhost",
                        user: config.server_username,
                        password: config.server_password,
                        database: config.database_name
                    });

                    con.connect((err)=> {
                        if (err){
                            console.log("Problem connecting to the DB!");
                            return;
                        }
                        console.log("Connected to the DB!");
                    });

                    con.query(sql_query, (err, result) => {
                        if (err) throw err;
                        console.log('Data received from the DB');
                        console.log(result);
                        resolve();
                        return result;
                    });

                    con.end((err) => {});

                })();
            });
        }
    };

但当我运行这个时,我得到的是:

[ Promise { <pending> } ]

我只是需要一些帮助,以便结果回来,然后代码继续。

xxls0lw8

xxls0lw81#

您不需要在同一段代码中使用promises和async/await。尝试以下操作:

module.exports =
{
    connect_to_db: async function (sql_query)
    {
        let con = sql.createConnection({
            host: "localhost",
            user: config.server_username,
            password: config.server_password,
            database: config.database_name
        });

        con.connect((err)=> {
            if (err){
                console.log("Problem connecting to the DB!");
                return;
            }
            console.log("Connected to the DB!");
        });

        return await con.query(sql_query);
    }
};

然后

const connect_to_DB = require('DB_Connection');     
let sql_query = "SELECT * FROM table";
database_results.push(await connect_to_DB.connect_to_db(sql_query));
console.log(database_results);

注意,sice await 关键字id只允许在内部 async 函数,该行 database_results.push(await connect_to_DB.connect_to_db(sql_query)); 应该在异步函数中才能工作

slhcrj9b

slhcrj9b2#

根据我的观点,解决这个问题的最佳方法是在node js中使用回调。
node js同步执行代码,让我解释一下代码中发生了什么

database_results.push(connect_to_DB.connect_to_db(sql_query));
console.log(database_results);

在代码控制台中,在执行函数connect\u to\u db.connect\u to\u db(sql\u query))之前返回log(数据库\u结果)
您的dbconnection.js可以修改为:

const sql = require('mysql');

exports.connect_to_db = function (sql_query, callback) {
let con = sql.createConnection({
    host: "localhost",
    user: config.server_username,
    password: config.server_password,
    database: config.database_name
});

con.connect((err) => {
    if (err) {
        console.log("Problem connecting to the DB!");
        return;
    }
    console.log("Connected to the DB!");
});

con.query(sql_query, (err, result) => {
    if (err) callback(err);
    console.log('Data received from the DB');
    console.log(result);
    callback(result);
});

con.end((err) => { });
};

调用函数connect\u to \u db的外部js可以修改为:

'use strict';

const connect_to_DB = require('DB_Connection');
let sql_query = "SELECT * FROM table";
connect_to_DB.connect_to_db(sql_query, function (data, err) {
  if (err) {
    console.log(err);
  }
  else {
    database_results.push(data);
  }
});

console.log(database_results);

要了解有关回调的更多信息,请访问

相关问题