Node.js loop malfunctioning is causing issues

Having some trouble with my Node.js for loop not functioning synchronously. Looking for assistance, thanks in advance!

Below is the code snippet:

 notifyRide:function*(body){
  yield User.find({_id: {$ne: body.userId}}, function(err, doc){
   if(doc != null){
    User.findOne({_id: body.userId}, function(err, user){
     Ride.findOne({_id : body.rideid}, function*(err1, ride){
      for (var i = 0; i < doc.length; i++) {
       console.log(i)// getting 0
       yield rideStatus.findOne({$and:[{receiver_id:doc[i]._id},{ride_id:body.rideid}]}, function(err, response)
       {
         console.log(i);//getting 1
       })
      }
     })
   })
  }
})

}

Answer №1

When working with generator-based coroutines, it is important to utilize the promises returned by Mongoose methods instead of relying on nested functions. You can find more information about using promises in Mongoose at:

For instance, rather than:

Ride.findOne({_id : body.rideid}, function*(err1,ride) ...

You should use:

let ride = yield Ride.findOne({_id : body.rideid});

To avoid complications with generators and ensure that your yielded values are not ignored.

Additionally, if you plan to work with generator-based coroutines, be sure to properly wrap your generator functions. For example:

notifyRide:function*(body) {
  // ...
}

You may want to consider using co like this:

notifyRide: co.wrap(function* (body) {
  // ...
})

or Bluebird like this:

notifyRide: P.coroutine(function* (body) {
  // ...
})

Alternatively, you can explore using async and await:

notifyRide: async (body) => {
  // ...
  // Use 'await' instead of 'yield'
}

Remember that coroutines themselves always return promises.

Lastly, don't forget to maintain proper indentation. It is highly recommended to adhere to a style guide such as the one provided by Airbnb:

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

What is the best way to insert a newline in a shell_exec command in PHP

I need assistance with executing a node.js file using PHP. My goal is to achieve the following in PHP: C:proj> node main.js text="This is some text. >> some more text in next line" This is my PHP script: shell_exec('node C:\pr ...

Install all dependencies again by running `npm install -g download`

My package.json file includes a list of 10 dependencies. Whenever I run npm install -g, all the dependencies get downloaded again, causing delays due to the lengthy process. I am wondering if there is a way to utilize the existing dependencies stored in ...

end the node.js automated testing process

I'm currently using Jasmine and Zombie JS to create automated tests. I have integrated Drone.io for Continuous Integration, and the tests are executing successfully. However, there seems to be an issue where after passing the tests, the process does n ...

Differences Between Put and Post in Node.js

I am currently exploring NODEJS in conjunction with react. In a typical scenario, the request to edit posts would look like this: router.put("/:id", function(req, res) { Campground.findByIdAndUpdate(req.params.id, req.body.campground, function( e ...

Launching a Node.js application automatically on startup with Ubuntu, Vagrant, and Puphpet

I have recently configured a node.js app on an Ubuntu environment using Vagrant/Puppet (generated from puphpet.com). Now, I need to send the finalized package to someone and ensure that the node.js app automatically starts running once they finish executin ...

What is the reason behind the timeout of an API request made to a local installation of Gitea?

I'm currently facing an issue while migrating a private github repository to my locally installed instance of Gitea. In order to accomplish this, I've set up a Docker container on a NAS in my home. Initially, I attempted to use the built-in migra ...

Error message saying 'Callback has already been invoked' returned by an async waterfall function

I'm facing an error that I understand the reason for, but I'm unsure how to resolve it. Here's a breakdown of my initial function: Essentially, I am making a get request for all URLs stored in the database and then, for each URL response, I ...

Having trouble getting the mock module to work with mockImplementation

I have been facing a challenge in properly testing this File. Some tests require mocking the entire module, while others only need specific methods mocked. I have tried various combinations, but currently, for one specific test below, I am attempting the f ...

The JWT Cookie has successfully surfaced within the application tab and is now being transmitted in the request

When sending a JWT token to an authorized user in Express, the following code is used: The cookie-parser module is utilized. module.exports.getUser = async (req, res, next) => { console.log('i am in getuser'); const { SIT } = req.query; ...

Unable to access the swagger JSON located at http://localhost:3000/sw-import.js/resources

I'm completely new to the world of node and swagger, so I decided to dive into loopback.io examples in order to build my own API. After successfully installing node and strongloop on my computer, I went ahead and created a fresh loopback application. ...

Utilizing MongoDb and Node.js for efficient data input

I am currently facing an issue while trying to input data into a mongodb collection using node.js. I believe I have the necessary access to the collection in question. var collection = db.collection("whatsGoingOnEvents"); if(collection){ console.log("hitt ...

Troubleshooting issues with my node.js API integration with MongoDB Atlas using Mongoose

IMPORTANT UPDATE : After investigating, I've realized that the issue is not with my code but rather with my work network which seems to be blocking the connection. I had to use my phone's data connection to figure this out. I will look into reso ...

Express authentication with repetitive login prompts appearing endlessly

Currently, I am in the process of password-protecting my node.js application using http-auth. Numerous individuals have faced similar issues, and I have attempted various solutions to address the problem. However, I seem to be encountering a roadblock. Whi ...

ERROR: The secure connection certificate for localhost is self-signed

While working on localhost, I encountered an error with nodemailer that resulted in an internal server error (500): ERROR: SELF_SIGNED_CERT_IN_CHAIN A thread discussing this issue can be found here: Npm SELF_SIGNED_CERT_IN_CHAIN on Azure. It suggested the ...

Utilize the Google Drive API to easily upload an Excel file

I'm encountering an issue with the Google Drive API. I've been attempting to upload an Excel file using this API, but haven't had any success. I even tried following the instructions in the Google API documentation without luck. Below is a ...

React JS - CORS error persists despite implementing cors settings

Currently utilizing Express and ReactJS Express Code: const Express = require('express'); const PORT = 5000; const cors = require('cors'); const server = Express(); server.use(cors()); // CORS added here server.get('/users&ap ...

Encountering chainId error when using ganache-cli with web3.eth.getTransaction

Every time I use ganache to call eth_getTransactionByHash, I encounter the following error message: "UnhandledPromiseRejectionWarning: Error: Incompatible EIP155-based V 1 and chain id 1. See the second parameter of the Transaction constructor to set the c ...

I'm having trouble with my express sessions not persisting and instead a new session (or multiple sessions) being created for each request. What could be causing this

I am encountering an issue with my node.js express app where the sessions are not persisting and a new session is created for every request. If anyone can help me understand why this is happening, I would greatly appreciate it. Due to the size of the app, ...

Currently, I am working with Angular 11 and encountered some errors while trying to embark on a new project

Command: ng serve Error: Cannot find module '@angular-devkit/build-angular/package.json' View details in "/tmp/ng-lQbnUK/angular-errors.log". These errors occurred when I tried to create the project: Installing packages (npm)... npm WARN depreca ...

The Socket.io client establishes connections with multiple servers simultaneously

Imagine this scenario: I am using nodejs and socket.io, and a question comes to mind. What would happen if one client establishes connections with multiple servers like this: socket = io.connect('http://server1') //600k sockets already connecte ...