我有一个函数,每次调用函数时都会返回一个未定义的对象。我想知道是否有一种解决这个问题的具体方法。在index.js中,我调用sqlQuery.getItem方法并期望它从db返回一行,但每次都返回undefined。
index.js
'use strict';
const Alexa = require('alexa-sdk');
const mysql = require('promise-mysql');
const querydb = require('./sqlQuery.js');
var testSQL = 'SELECT uWeight, uHeight from users where pin=1100';
//querydb.getItem(testSQL);
var values = querydb.getItem(testSQL);
if(values == undefined){
console.log('Error');
}
else{
console.log(values);
}
databaseConnection.js
var mysql = require('promise-mysql');
pool = mysql.createPool({
host: "mytrainerdb.cbh07n2xwds2.us-east-1.rds.amazonaws.com",
database: "trainerdb",
user: "user",
password: "password"
});
function getSqlConnection() {
return pool.getConnection().disposer(function(connection) {
pool.end(connection);
});
}
module.exports = getSqlConnection;
sqlQuery.js
var Promise = require("bluebird");
var getSqlConnection = require('./databaseConnection');
var hello = "hello";
function getItem(sql){
Promise.using(getSqlConnection(), function(connection) {
return connection.query(sql).then(function(rows) {
console.log(rows[0]);
return (rows[0]);
}).catch(function(error) {
return (error);
});
})
}
module.exports.getItem = getItem;
答案 0 :(得分:2)
function getItem(sql){
return Promise.using(getSqlConnection(), function(connection) {
return connection.query(sql).then(function(rows) {
console.log(rows[0]);
return (rows[0]);
}).catch(function(error) {
return (error);
});
})
}
注意第二行的回报?这会产生影响,但你仍然不会在值中得到实际值var values = querydb.getItem(testSQL);
,而是一个你要返回的承诺。如果promises成功进行了then
回调承诺对象,那么你将获得该值
var valuesPromise = querydb.getItem(testSQL);
valuesPromise.then(function(result) {
//use result here
})
或只是
querydb.getItem(testSQL).then(function(result) {
//use result here
})