Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7998987
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 4, 20262026-06-04T15:22:11+00:00 2026-06-04T15:22:11+00:00

I am working on the code snippet below. I have an array of JSON

  • 0

I am working on the code snippet below. I have an array of JSON objects called ‘stuObjList’. I want to loop through the array to find specific JSON objects with a certain flag set, and then make a database call to retrieve more data.

Of course, the FOR loop doesn’t wait for the database call to return and reaches the end of with j == length. And when the database call returns, the index ‘j’ is beyond the array index. I understand how node.js works and this is the expected behavior.

What is the workaround here? How can I achieve what I am trying to achieve?

...............
...............
...............
else
{
  console.log("stuObjList.length: " + stuObjList.length);
  var j = 0;
  for(j = 0; j < stuObjList.length; j++)
  {
    if(stuObjList[j]['honor_student'] != null)
    {     
      db.collection("students").findOne({'_id' : stuObjList[j]['_id'];}, function(err, origStuObj)
      {
        var marker = stuObjList[j]['_id'];
        var major = stuObjList[j]['major'];
      });
    }
    
    if(j == stuObjList.length)
    {
      process.nextTick(function()
      {
        callback(stuObjList);
      });
    }
  }
}
});
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-04T15:22:12+00:00Added an answer on June 4, 2026 at 3:22 pm

    “async” is an very popular module for abstracting away asynchronous looping and making your code easier to read/maintain. For example:

    var async = require('async');
    
    function getHonorStudentsFrom(stuObjList, callback) {
    
        var honorStudents = [];
    
        // The 'async.forEach()' function will call 'iteratorFcn' for each element in
        // stuObjList, passing a student object as the first param and a callback
        // function as the second param. Run the callback to indicate that you're
        // done working with the current student object. Anything you pass to done()
        // is interpreted as an error. In that scenario, the iterating will stop and
        // the error will be passed to the 'doneIteratingFcn' function defined below.
        var iteratorFcn = function(stuObj, done) {
    
            // If the current student object doesn't have the 'honor_student' property
            // then move on to the next iteration.
            if( !stuObj.honor_student ) {
                done();
                return; // The return statement ensures that no further code in this
                        // function is executed after the call to done(). This allows
                        // us to avoid writing an 'else' block.
            }
    
            db.collection("students").findOne({'_id' : stuObj._id}, function(err, honorStudent)
            {
                if(err) {
                    done(err);
                    return;
                }
    
                honorStudents.push(honorStudent);
                done();
                return;
            });
        };
    
        var doneIteratingFcn = function(err) {
            // In your 'callback' implementation, check to see if err is null/undefined
            // to know if something went wrong.
            callback(err, honorStudents);
        };
    
        // iteratorFcn will be called for each element in stuObjList.
        async.forEach(stuObjList, iteratorFcn, doneIteratingFcn);
    }
    

    So you could use it like this:

    getHonorStudentsFrom(studentObjs, function(err, honorStudents) {
        if(err) {
          // Handle the error
          return;
        }
    
        // Do something with honroStudents
    });
    

    Note that .forEach() will call your iterator function for each element in stuObjList “in parallel” (i.e., it won’t wait for one iterator function to finish being called for one array element before calling it on the next array element). This means that you can’t really predict the order in which the iterator functions–or more importantly, the database calls–will run. End result: unpredictable order of honor students. If the order matters, use the .forEachSeries() function.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am using the code snippet below, however it's not working quite as I
I have the following code snippet which is working fine: ifstream NDSConfig( NDS.config )
I have code snippet like below I am facing problem when I click on
Below is a code snippet from the file I am working with. I will
I have a sample code snippet below which works just fine (I trimmed the
I have found a code snippet as given below which is used to disable
I have working code of js, it shows different div for selected option. <html>
I have some working code with a crutch to add BOM marker to a
This is my Working Code DriftMul:=99; WriteProcessMemory(HandleWindow, ptr($4E709C), @DriftMul, 2, Write); I want to
I have this working code, but now i need to be able to change

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.