Search code examples
node.jsmongoosekoa

loop not working properly in node js


I am new to nodejs for loop not working synchronously. Please help thanks in advance

here is my code

 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
       })
      }
     })
   })
  }
})

}


Solution

  • Since you seem to be using generator-based coroutines, why won't you use the promises that are returned by Mongoose methods? See:

    For example, instead of:

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

    you can use:

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

    and avoid the nested functions. Otherwise you are yielding things not from the right generator and the yielded values get ignored.

    Also make sure that if you want to use generator based coroutines than you need to properly wrap your generator functions. For example:

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

    should probably be this with co:

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

    or this with Bluebird:

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

    Alternatively you can use async and await

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

    Note that the coroutines themselves always return promises.

    And for the love of God, use some indentation. I strongly recommend following a decent style guilde like the one by Airbnb: