Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

88
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!