Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

83
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda