What is the best way to make a for loop pause until a callback is complete in Node.js?

entry.find(function(err,user){
  for(var i=0;i<user.length;i++){
    if(user[i].tablenumber==-1){

       assigntable(user[i]);
    }
  }

});

In this code snippet, the goal is to ensure that each iteration of the for loop completes before invoking the asynchronous `assigntable` function. The purpose of `assigntable` is to modify the database by utilizing a callback function. However, the issue at hand arises from the fact that the `assigntable` function's callback is triggered after the completion of the for loop, resulting in all users being assigned to table 1. Instead, the desired behavior is as follows: assign the first user to table 1 -> upon the next iteration detecting table 1 has been assigned, proceed to assign the second user to table 2, and so on. How can this be achieved?

Edit: It should be noted that `Assgintable` is a recursive function that alters the database within a callback. While the update operation is conditional based on the outcome of the previous loop's database state, this detail might not be pertinent to the current discussion.

function assigntable(user,tableindex){
  console.log("in recursion with tableindex "+tableindex);
  if(tableindex==3)
    return;
  console.log(user.date + user.time + tableindex);
  entry.find({
      $and: [
          { "tablenumber": tableindex },
          { "date": user.date },
          { "time": user.time }
        ]
  }, function(err, result) {
      if(result.length==0){
        console.log(result+"result is ");
        entry.update({"_id": user._id}, {"tablenumber": tableindex}, function(err, numberAffected) {
          if(!numberAffected){

          }
          else
          {
            console.log("entry updated with "+tableindex)
          }
      });
      return;
  }
  else{
    console.log(tableindex);
    assigntable(user, tableindex+1);
  }
})

}

Answer №1

To loop through the items synchronously, you can utilize async.foreach:

entry.find(function(err,user){
  async.forEach(user, function (item, callback){ 
    if(item.tablenumber==-1){
       console.log(item);
       assigntable(item,1);
    }    
    callback(); 
  }, function(err) {
    console.log('iteration complete');
  })}).sort({datesubmitted:1});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to exclusively deploy the backend of my React Native app on Heroku?

I am currently developing a react native app with expo, using node.js and Express for the backend. My project structure consists of a frontend folder and a backend (server) folder within the root directory. Root | |Frontend |Various screens & assoc ...

Generate a customizable URL for my search bar

I have developed a single HTML page with full AJAX functionality, displaying all content including form submits, main page, form results, and more through various DOM manipulations. The issue I am currently encountering is related to a search box where use ...

What is the reason for the Circle to Polygon node module producing an oval or ellipse shape instead of a circle shape?

I've been experimenting with the npm package circle-to-polygon and I crafted the following code to generate a polygon that resembles a circle. const circleToPolygon = require('circle-to-polygon'); let coordinates = [28.612484207825005, 77. ...

Is there a way to generate a specific error using express-validator?

When working with form validation using the POST method, I encountered an issue regarding pushing an error into express-validator when an email address is already registered. This way, the error can be included when calling req.validationErrors(). Here&apo ...

Use Puppeteer and Node.js to repeatedly click a button until it is no longer present, then initiate the next step

Imagine a dynamic web page filled with rows of constantly updated data. The number of rows on the page remains fixed, meaning old rows are replaced and not stored anywhere. To navigate through this page, you need to click on a "load more" button that app ...

Transmit information to an AngularJS application instantly

Looking for a solution to keep my AngularJS app displaying real-time data without constantly querying my api. Is there a way to establish a connection between my server and the AngularJS app so that new data can be pushed from the server to the app for dis ...

Is it necessary for Webpack to package all dependent node modules with the final bundle in production mode?

It's common knowledge that when we run npm run build, React scripts utilize Webpack to create a bundle by examining the entire dependency graph (following imports) and generating a bundle.js which is then stored in the dist/build folder for production ...

Store the response data in a global variable or forward it to another function in Node.js using Express JS

I'm currently working on a function that makes a post request to an API (app.post), sending a token and a URL for redirection to webpay. The challenge I'm facing is saving that token in a global variable so that it can be accessed by another func ...

What is the best way to display a User Story's Revision History within a grid format?

I stumbled upon a solution concerning Revision History from this thread. However, I'm struggling with figuring out how to fill a grid with this information. Is it possible to utilize the model and populate a story that the grid is pulling from? ...

The dynamic duo of applications in expressjs

Currently, I am in the process of developing an application using express js that will cater to various clients such as web and mobile. I have made the decision not to use a single app for both client types due to concerns about added burden from certain ...

Error message encountered in node-schedule: Unable to read undefined property upon job restart

Using node-schedule, I have successfully scheduled jobs on my node server by pushing them into an array like this: jobs.push(schedule.scheduleJob(date, () => end_auction(req.body.item.url))); Everything is working as expected. When the designated date ...

What is the memory allocation for null values in arrays by node.js?

Continuing the discussion from this thread: Do lots of null values in an array pose any harm? I experimented with node.js by doing this: arr=[] arr[1000]=1 arr[1000000000]=2 arr.sort() However, I encountered the following error: FATAL ERROR: JS Alloca ...

What is the method to access the controller value within a metadata tag?

One of the challenges I am facing is how to access a variable from a controller and use it in a metadata tag using AngularJS. Below is my approach: First, let's define the variable in the controller: app.controller('homeCtlr', function($sc ...

Saving the authenticated user's information from Firebase (including first name, last name, gender, and more) directly to our database

I am utilizing firebase authentication for user registration and login. Upon registration/login, I aim to save additional user details (such as FirstName, LastName, Gender, etc.) in my database. Currently, I have a process in place to achieve this. Howeve ...

Is there a way to retrieve the filename from a callback in gulp-contains?

Currently, I am utilizing gulp-contains to scan for a specific string. If the target string is found, I intend to trigger an error message stating "String found in file abc." The 'file' parameter holds the entire object comprising filename + Buff ...

The sequence of express routing does not transition automatically from a POST request to the next GET request

I have the following route defined: router.post('/select', function(req, res, next){ var sql = "SELECT metadocid, col1, col2, col3 FROM mdt1 where "; var metadocid = req.body.metadocid; var op1 = req.body.op1; if (metadocid !== "") ...

Checking if a certain function has been called within my express controller function

As a testing newcomer, I am still learning the necessary skills. I have been working on testing my error handler controller and after some time, I finally got it up and running. However, I would appreciate some feedback on the implementation. There seems ...

There seems to be a lack of response from the Foursquare API in Node.js

Seeking guidance on retrieving a photo from a Foursquare venue using Node.js platform. Despite having the correct id and secret, the code is returning an unexpected result. My goal is to obtain the prefix and suffix of the image to properly display it as o ...

What distinguishes pre-save and validate methods in mongoose? How do you decide when to utilize each one?

Currently, my validation process involves using the pre('save') method: UserSchema.pre('save', true, function(next, done) { var self = this //in case inside a callback var msg = helper.validation.user.username(self.username) ...

My date function in Node JS is throwing an error, can someone please help me troubleshoot?

I encountered an error with new date(); while working with node js and express npm plugin. I built a variable date but faced some compilation errors. This is my code .js var update_time = new Date(); update_time.formatDate("y/m/d"); When I run ...