This question already has an answer here:
- Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference 3 answers
I could not figure out why my userProjects
at the end prints an empty array.
var express = require('express');
var router = express.Router();
var idea = require("../models/idea_model");
/* GET home page. */
router.get('/', function (req, res, next) {
//var sess = req.session;
var userProjects = []
try {
if (sess.user.email) {
console.log("see.user.projects: " + sess.user.projects);
var proj_length = sess.user.projects.length;
for (var i = 0; i < (proj_length); i++) {
console.log("project name: " + typeof (sess.user.projects[i]) + " " + sess.user.projects[i]);
idea.findOne({
title: sess.user.projects[i]
}, function (err, docs) {
if (!err) {
if (!docs) {
console.log("error saving project to user");
} else {
userProjects.push(docs);
}
} else {
console.log(err);
}
});
}
console.log("vvvvvvvvvvvvvvvvvvvvvvvvvvvv");
console.log(userProjects); //Problem!!!!!!!!!!!!!!! empty array!!!
res.render('user_dash', {
user_proj: JSON.stringify(userProjects)
});
if (sess.cookie.maxAge <= 0) {
sess = null;
}
}
} catch (e) {
res.render('login');
}
});
module.exports = router;
Aucun commentaire:
Enregistrer un commentaire