我是 Javascript 的新手,我试图创建一个函数来返回我从我的数据库中获得的一个数组。首先我尝试了这个:
function getItens(userId){
var arr = new Array;
var result;
var connection = mysql.createConnection({
host : 'localhost',
user : 'XXXXXX',
password : 'XXXXXX',
database : 'XXXXXX',
});
connection.connect();
connection.query('SELECT * from itens where userId = '+ userId function(err, rows, fields){
if (err) throw err;
arr = rows.slice()
});
return arr;
connection.end();
}
然后我意识到那里存在范围问题,经过一些研究后,我尝试模拟这样的静态变量:
function getItens(userId){
(function (){
var resultado;
Result = function(valor) { resultado = valor; };
Result.prototype.getResultado = function (){return resultado};
Result.prototype.setResultado = function (valor){ resultado = valor; };
})();
var ar = new Result([]);
var connection = mysql.createConnection({
host : 'localhost',
user : 'XXXXXX',
password : 'XXXXXX',
database : 'XXXXXX',
});
connection.connect();
connection.query('SELECT * from itens where userId = '+ userId , function(err, rows, fields){
if (err) throw err;
ar.setResultado(rows.slice());
});
return ar.getResultado();
connection.end();
}
但它没有用,我做错了什么?