我无法使此代码生效,我试图从我的数据库中生成5个randoms项目并将它们存储到数组中(dato),但是当我打印它时似乎是空的
/* GET users listing. */
router.get('/', function (request, response) {
var dato = new Array();
for(var i=0;i<7;i++){
almuerzoSchema.findRandom({}, {}, {limit: 5}, function(err, results) {
if (!err) {
results.forEach(function (record) {
dato.push(record.nombre);
});
}
});
}
console.log(dato);
response.render('almuerzo.jade',{almuerzovar: dato});
});
console.log(dato)显示:
[]
如果我打印&#34; record.nombre&#34;在console.log上它显示正确
答案 0 :(得分:2)
/* GET users listing. */
router.get('/', function (request, response) {
var dato = new Array(), promises =[];
for(var i=0;i<7;i++){
promises.push(promisifiedFindRandom())
}
Promise.all(promises).then(function(){
console.log(dato);
response.render('almuerzo.jade',{almuerzovar: dato});
})
function promisifiedFindRandom(){
return new Promise(function(resolve, reject){
almuerzoSchema.findRandom({}, {}, {limit: 5}, function(err, results) {
if (!err) {
results.forEach(function (record) {
dato.push(record.nombre);
});
resolve();
}else{
resolve();
}
});
})
}
});
编辑:本地v4 +支持承诺,对于旧版本,您可以使用polyfill / shim