0

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

})
3
  • You should use promises. Commented Feb 22, 2018 at 17:50
  • I'dont know how to implement it here Commented Feb 22, 2018 at 17:51
  • You should use Promise.all(). Commented Feb 22, 2018 at 17:52

1 Answer 1

2

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

    });

}
Sign up to request clarification or add additional context in comments.

1 Comment

Use Promise.all() instead of writing all of that logic yourself.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.