gpt4 book ai didi

mysql查询循环 Node js

转载 作者:行者123 更新时间:2023-11-29 10:22:44 25 4
gpt4 key购买 nike

问题是查询在循环内是异步的,如果我在 for 查询尚未执行之后执行某些操作,我需要在 for 和所有查询完成时执行某些操作

   app.post('/consulta',(req,res)=>{
var data = req.body.frase;
let consulta;
let respuesta = [];

for(let i=1;i<data.length;i++){
consulta = `SELECT * FROM imagen WHERE nombre = "${data[i-1] +' '+ data[i]}"`;
connection.query(consulta, function (error, results, fields) {
if (error) throw error;

if(results.length > 0){ // Si existe una seña que tenga 2 palabras
data[i-1] = data[i-1] +" "+data[i]; // Unidos jamas seran vencidos
data.splice(i, 1);
}
});
}

})

最佳答案

尝试这样做:

app.post('/consulta',(req,res)=>{
var data = req.body.frase;
let consulta;
let respuesta = [];

query(data).then(result => {

// implement your success case...

}).catch(err => {
//throw exception here...
});

});

function query(data){

return new Promise((resolve, reject) => {

var counter = 0;

if (data.length > 0){

for(let i=1;i<data.length;i++){

consulta = `SELECT * FROM imagen WHERE nombre = "${data[i-1] +' '+ data[i]}"`;

connection.query(consulta, function (error, results, fields) {
if (error) reject(error); //terminate the promisse...

if(results.length > 0){ // Si existe una seña que tenga 2 palabras
data[i-1] = data[i-1] +" "+data[i]; // Unidos jamas seran vencidos
data.splice(i, 1);
}

counter++;

if (counter >= data.length){
resolve("Everything OK");
}

});

}

} else {
reject("There are no data"); //terminate the promise...
}

});

}

关于mysql查询循环 Node js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48934070/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com