正如标题所示,我无法从connection.query()
函数之外的MySQL响应中访问对象。
router.get('/', function(req, res) {
var testimonials;
// Running database queries
connection.query('SELECT * FROM testimonials', function(err, rows, fields) {
if (!err) {
testimonials = rows;
console.log(testimonials); // THIS WORKS
}
if (err) {
console.log('Error performing database query.');
}
});
res.render('index', {
title: 'Title',
description: 'Description in here.',
testimonials: testimonials // THIS RETURNS UNDEFINED
});
});
答案 0 :(得分:0)
您应该将res.render
放在回调函数中,例如:
router.get('/', function(req, res) {
var testimonials;
// Running database queries
connection.query('SELECT * FROM testimonials', function(err, rows, fields) {
if (!err) {
testimonials = rows;
res.render('index', {
title: 'Title',
description: 'Description in here.',
testimonials: testimonials // this will work!!!
});
}
if (err) {
console.log('Error performing database query.');
}
});
});
注意:在回调函数之外使用undefined
时会得到testimonials
,因为方法connection.query
是异步的,并且>> <{strong>之后<{>} res.render
方法。