我正在为客户编写此代码作为项目 当我去表演路线时,我收到了 500 内部服务器错误
http.get('/files/:id', function(req, res) {
var vid;
var pap;
Videos.find({}, function(err, videos) {
if (err) {
console.log(err);
} else {
vid = videos;
}
});
Papers.find({}, function(err, file) {
if (err) {
console.log(err);
} else {
pap = file;
}
});
Material.findById(req.params.id, function(err, found) {
if (err) {
console.log(err);
} else {
res.render('files', {
file: pap,
video: vid,
current: found
});
}
});
});
这是我的演出路线代码。
注意:如果我重新加载页面,错误就会消失并且页面会打开。
最佳答案
原因是您需要等待所有数据库查询完成才能渲染。在您的代码中,页面可能会在其他两个查询完成并返回数据之前呈现。好消息是Mongoose supports Promises对于异步函数。
http.get('/files/:id', function(req, res) {
Promise.all([
Videos.find({}).exec(),
Papers.find({}).exec(),
Material.findById(req.params.id).exec()
]).then( ([video, paper, material]) => {
res.render('files', {
file: paper,
video: video,
current: material
});
}).catch( error => console.log(error) );
});
关于javascript - 我的nodejs代码出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41413000/