【发布时间】:2019-04-23 18:19:10
【问题描述】:
我有一个 .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> } ]
我只是需要一些帮助才能返回结果,然后代码才能继续。
【问题讨论】:
-
你怎么知道'con'已经准备好使用了,createConnection在进行con.connect之前可能没有完成,你可以在使用前向控制台显示'con'吗?
-
你的权利,con.connect调用前后的状态是断开连接
-
您能否等待连接并在失败或成功时采取适当的措施?
-
您能否提供一些示例代码,因为我尝试过 await con.connect 无济于事。
-
对不起,我对你使用的API不熟悉,必须有某种等待或回调的方式来对结果进行操作。
标签: javascript mysql node.js promise