Benson OO
Benson OO

Reputation: 517

Node js callback issue

In my NodeJS application, I am building an API that first fetches all tarrifs name from tarrifs collection then based on all those tarrifs I want to return the counts of these tariffs allocated to users I tried the below-given code

router.get('/getTarrifDetails', (req,res,next) => {
     result=[];
     tname=[];
     counts=[];

     Tarrif.find().distinct('tarrif_type', (err,docs) => {
       docs.forEach((ele) => {
         tname.push(ele);

         User.countDocuments({tarrif_type:ele}, (uerr,usr) => {
             counts.push(usr);
         });

         result.push(ele);
     });

     result.push(counts);
   });
});

When I console.log(result) it only shows one array of tarrif_type and other array is empty

Upvotes: 0

Views: 73

Answers (1)

Vijay Gaikwad
Vijay Gaikwad

Reputation: 467

You need to understand how the event loop works. I was here once, and I made the same mistakes once.

Try to sync your callbacks since you want to sequentially, like so:

  router.get('/getTarrifDetails', (req, res, next) => {
    let result = [], count = 0;
    Tarrif.find().distinct('tarrif_type', (err, docs) => {
      async.forEach(docs, async ele => {
        try {
          let userCount = await User.countDocuments({ tarrif_type: ele });
          result.push(userCount);
        } catch (err) {
          //your err goes here.
        }
      })
    });
  });

I am not sure this will work 100%, but try it out and debug a little bit.

Upvotes: 1

Related Questions