如何在变量中存储Node mysql查询? [英] How to store Node mysql query in a variable?
问题描述
我正在使用节点mysql连接到外部数据库,并且可以 console.log
查询结果,但是当我尝试返回数据时,我得到 Promise未决
.
I'm using node mysql to connect to an external DB and I can console.log
the query results but when I try to return the data I get Promise pending
.
这是函数-
export function get_info() {
var mysql = require('mysql');
var connection = mysql.createConnection({
host: 'xxxxxx',
user: 'bob',
port: 'xxxx',
password: 'bob',
database: 'li_webform'
});
connection.connect(function (err) {
if (err) throw err;
connection.query("SELECT Name FROM webform", function (err, result) {
if (err) throw err;
//console.log(result); **This works**
//console.log(result[0].Name);
return result;
});
});
}
我正试图像这样将变量设置为等于返回值
I'm trying to set a variable equal to the return value like this
var newVar = get_info();
console.log(newVar);
但是我得到了未完成的诺言.我相信这与JavaScript的异步性质有关.我已尝试按照此帖子如何正确返回mysql和Node一起导致的结果?但无法正常工作.
but I got the promise pending note. I believe this has something to do with the Asynchronous nature of JavaScript. I've tried following this post How to properly return a result from mysql with Node? but can't get it working.
这是我按照该帖子尝试的内容
Here is what I tried following that post
export function get_info(callback) {
var mysql = require('mysql');
var connection = mysql.createConnection({
host: 'xxxxx',
user: 'bob',
port: 'xxxxxx',
password: 'bob',
database: 'li_webform'
});
connection.connect(function (err) {
if (err) throw err;
connection.query("SELECT Name FROM webform", function (err, result) {
if (err) throw err;
//console.log(result);
//console.log(result[0].Name);
return callback(result);
});
});
}
然后我尝试通过
var stuff_i_want = '';
get_info(function (result) {
stuff_i_want = result;
console.log(stuff_i_want);
});
但是我没有输出
编辑**这是新尝试
export function get_info() {
var mysql = require('mysql');
var connection = mysql.createConnection({
host: 'xxxx',
user: 'bob',
port: 'xxxxxx',
password: 'bob',
database: 'li_webform'
});
connection.connect(function (err) {
if (err) throw err;
connection.query("SELECT Name FROM webform", function (err, result) {
if (err) throw err;
//console.log(result);
//console.log(result[0].Name);
return result;
});
});
}
第二部分
get_info().then((callbackData)=>{
console.log("Data: ", callbackData)
}).catch((error)=>{
console.log("Error", error)
});
推荐答案
该函数返回一个Promise.您可以这样处理:
The function returns a promise. You can handle it like this:
get_info().then((callbackData)=>{
console.log("Data: ", callbackData)
}).catch((error)=>{
console.log("Error", error)
});
这篇关于如何在变量中存储Node mysql查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!