我是初学者进入nodeJS世界,我尝试连接mysql数据库。我首先选择一个团队(equipe),之后我必须选择该团队的所有成员。
最后,我想用我的团队和成员构建一个数组(在lesEquipes var中)。当代码到达第3个时,我的var为null!为什么好吗?
这是我的代码:
class Database {
constructor() {
this.connection = mysql.createConnection({
host: "192.x.x.x",
user: "john",
password: "mypass",
database: "mybase"
});
}
query(sql, args) {
return new Promise((resolve, reject) => {
this.connection.query(sql, args, (err, result, fields) => {
if (err) return reject(err);
resolve (result);
});
});
}
close() {
return new Promise((resolve, reject) => {
this.connection.end(err => {
if (err) return reject (err);
resolve();
});
});
}
}
var database = new Database();
.............
app.post('/visu',function(req,res){
//console.log(nodedump(req.params.mdp));
//console.log(req.body);
// codage en dur de l'authentification
if((req.body.email == "john@gmail.com") && (req.body.mdp == "password")){
var leUser = "administrateur";
let lesEquipes = new Array();
let test = 'Toto';
database.query("select * from equipe order by id")
.then( result => {
for (var i = 0; i < result.length; i++) {
let courante = new Array();
let nomEquipe = result[i].nomEquipe;
let idEquipe = result[i].id;
courante[0] = result[i];
var sql2 = "select * from participant where equipe = " + result[i].id;
//console.log(sql2);
database.query(sql2)
.then(result2 => {
console.log("Membres de l'équipe : " + nomEquipe);
courante[1] = result2;
console.log("COURANTE 2 "+ JSON.stringify(courante));
lesEquipes[idEquipe] = courante;
let test = 'AUTRE CHOSE';
/*
console.log("QUERY 2 "+ JSON.stringify(result2));
for (var j = 0; j < result2.length; j++) {
participant = result2[j].nom;
console.log(participant);
}
*/
//res.render('visuEquipes.ejs', { user:leUser, equipes:lesEquipes});
//console.log("Contenu "+ JSON.stringify(lesEquipes));
return ""; //database.query(sql3);
});
}
console.log("Contenu "+ JSON.stringify(test));
console.log("Contenu "+ JSON.stringify(lesEquipes));
}).then(result3 =>{
console.log("result 3 : "+result3);
console.log("Contenu "+ JSON.stringify(test));
**// THIS VAR IS NULL NULL NULL lesEquipes
console.log("Contenu "+ JSON.stringify(lesEquipes));**
res.render('visuEquipes.ejs', { user:leUser, equipes : lesEquipes});
}).catch((err) => {
console.log(err);
database.close();
});
答案 0 :(得分:0)
问题是你在循环中执行异步代码。
multipartFormData.append(imageData!, withName: "product_image[\(index)]", fileName: "\(index).jpg", mimeType: "image/jpg")
因此,在for (var i = 0; i < result.length; i++) {
/**/
database.query(sql2).then(result2 => {
/**/
});
}
中,变量.then(result3 =>{
很可能尚未初始化。
你必须等待所有的承诺才能解决。您可以轻松添加一系列承诺。
lesEquipes
或者您可以使用const promises = [];
for (var i = 0; i < result.length; i++) {
promises.push(database.query(sql2).then(result2 => {/*...*/}));
}
return Promise.all(promises);
库来迭代数组,或者更好地使用ES7 async-p
构造。