Kabilesh
Kabilesh

Reputation: 1012

async in node js is not working

I am trying to run two different mongoose queries and display the result in same ejs page. I searched a lot and finally found the async method. How I tried this is below.

js file

router.get('/CreateSurvey', function(req, res, next) {

async.parallel([
        function(callback) {
            QBank.find( function ( err, classes, count ){
                classes : classes  
            });
        },
       function(callback) {
            QBank.findOne({_id:"H001"},  function ( err, questions, count ){     
                questions : questions
            });
        }
    ], function(err) { 
        if (err) return next(err);
        res.render('CreateSurvey', QBank);
    });

});

But when I refresh '/CreateSurvey' page it does not render. I have already downloaded async module and required in my js file. Where am I wrong?

Upvotes: 0

Views: 285

Answers (3)

Harpreet
Harpreet

Reputation: 1

if you prefer using Promises (which is more modern and might be simpler), you can use Promise.all:

router.get('/CreateSurvey', async function(req, res, next) {

try {
    const classesPromise = QBank.find().exec();
    const questionsPromise = QBank.findOne({_id: "H001"}).exec();

    const [classes, questions] = await Promise.all([classesPromise, questionsPromise]);

    res.render('CreateSurvey', { classes: classes, questions: questions });
} catch (err) {
    next(err);
}})

Upvotes: 0

Mukesh Sharma
Mukesh Sharma

Reputation: 9032

There are some issues with the code, you aren't calling callback corresponding to async call. Try the following:

router.get('/CreateSurvey', function(req, res, next) {
  async.parallel({
    classes: function(callback) {
      QBank.find(function(err, classes, count){
        callback(classes);
      });
    },
    questions: function(callback) {
      QBank.findOne({_id:"H001"},  function (err, questions, count ){     
        callback(questions);
      });
    }
  }, function(err, result) { 
    if (err) return next(err);
    res.render('CreateSurvey', result); // { classes : [c1, c2] , questions : [q1, q2] }
  });
});

Upvotes: 1

Santanu Biswas
Santanu Biswas

Reputation: 4787

Firstly, What is that classes : classes and questions : questions lines in your code? What are you trying to do?

The callback parameter of each task function (the functions in array) should be called inside the task to indicate completion of each task with success or error.

The optional main callback (the third function in your code), where you are doing the actual rendering, will be called only after all the tasks have completed.

In your code callback is not called inside the task. As a result the final callback is also never getting called. In fact, in your code only the first *task gets executed and nothing happens beyond that.

Read more about async.parallel in documentation

Upvotes: 1

Related Questions