albeiro
albeiro

Reputation: 21

mysql query inside loop node js

The problem is that the query is async inside loop, i need to execute something when the for and all the queries finished, if i execute something after the for the queries wasn't executed yet

   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);
            }
        });
    }

})

Upvotes: 0

Views: 812

Answers (1)

pedro.olimpio
pedro.olimpio

Reputation: 1498

try to do this:

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...
        }

    });

}

Upvotes: 2

Related Questions