-1

Suppose I have a route that looks like this

router.post('/:subject_ID', (req, res) => {

    // First Query
    Student.findOne({student_ID: req.body.student_ID})
    .exec()
    .then()
    .catch();

    // Second Query
    Subject.findById(req.params.subject_ID)
    .exec()
    .then()
    .catch();

});

I want to use some data in the 2nd query that will be returned by the 1st query. But right now I'm not able do that since based on my understanding (correct me if I'm wrong) both queries are promises and works asynchronously so it won't wait for the 1st query's completion to execute the 2nd query.

How will I rewrite this that the execution of the 1st query will always be finished first before executing the 2nd query?

thegreathypocrite
  • 2,293
  • 5
  • 15
  • 20

1 Answers1

1

Just place it inside of the other then()

router.post('/:subject_ID', (req, res) => {
    // First Query
    Student.findOne({student_ID: req.body.student_ID})
    .exec()
    .then(result=>{
      // Second Query
      return Subject.findById(req.params.subject_ID).exec();
    }).then(result2=>{
      res.render(...);
    })
    .catch();
});

Or use async/await, if available:

router.post('/:subject_ID', async (req, res) => {
 try{
    // First Query
    let result = await Student.findOne({student_ID: req.body.student_ID}).exec();
    let result2 = await Subject.findById(req.params.subject_ID).exec();
    res.render(...);
  }catch(e){
  }
});
Cody G
  • 8,368
  • 2
  • 35
  • 50