Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

82
Vistas
Loop finishing before nested mongoose functions complete

All, I am writing a post function that has includes a for loop with three nested mongoose functions (findOne, findById & create). However, it appears as if the functions are not being completed before moving on to the next "i". This is evidenced by the fact that the console.log of this code, never equals 5. I have done a decent amount of research and understand the issue is that these mongoose functions are asynchronous, but I have yet to come across the problem where people have three nested functions like below. Is there any way to allow the functions to finish before progressing through the loop?

Thanks!

For simplicity sake, I have put i < 5, although this is represented by a variable in my code. Furthermore, lets assume that price is greater than sellYesPricesMin.

var quantity = 0;
if(price >= sellYesPricesMin){
    for (i = 0; i < 5; i ++){
        if(price >= sellYesPricesMin && sellYesPricesMin>0){
            Order.findOne({"yes_or_no":"NO", "buy_or_sell":"BUY","event.id":req.params.id},function(err, foundOrder){
                if(err){
                    console.log(err);
                } else {
                    User.findById(foundOrder.author.id, function(err, foundUser){
                        if(err){
                            console.log( err);
                        } else {
                            Share.create({}, function (err, newShare) {
                                if (err){
                                    console.log(err);
                                    quantity = quantity + 1;
                                    sharesCreated++;   
                                    campground.shares.push(newShare);    
                                    campground.save();
                                    foundUser.save();
                                }
                            });
                        }
                    });
                }
            });
        } else {    
            campground.buyYesPrices.push(parseFloat(Math.round(price * 100) / 100).toFixed(2));            
            req.user.save();
            campground.save();
        }
        req.user.save();
        campground.save();
    }
    console.log("QUANTITY: " + quantity);
} else {
    // BLAH BLAH BLAH
}
over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

According to above scenario, What I understand is that you want to access certain variable outside the functions in a state as if these functions were executed synchronously.

You can bind those variables to these functions and these execution will work the way you want them to execute.

I'm writing a small code which will help you to understand the concept.

for (var i = 0; i < 10; i++) {

    asynccall("Hello", function (others, err, data) {
        console.log("Others is same as i in synchrnous call " + others);
    }.bind(this, i));
}
over 4 years ago · Santiago Trujillo Denunciar

0

Since all of these calls are asynchronous, it will basically do it all at once and it wont wait for any one section to finish. Therefore it is probably doing it out of order. For me its easier to think of it as a bunch of different threads. You might have to basically pause the asynchronous part on this one section if you need it to run in order.

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda