简体   繁体   中英

Query multiple database calls with then in NodeJS

I'm working on a JS route handler. Basically, when a user click on a button it jumps to the next page with his information and the devices that he can check out.

router.get('/userManagement/:id', function(req,res){
  var idNumber = req.params.id;
  var registeredDevices = dbAPI.registeredDevices(true);
  dbAPI.getInfoUser(idNumber).then(function(ret){
    console.log(ret);
    console.log(registeredDevices);
    res.render('userManagement.njk', {obj: ret});
  })
});

ret returns a JSON of the user information and console.log does show the JSON file correctly, but registeredDevices is displayed as Promise object. Why is that? How could I get the JSON from that function call?

Thanks

I'm sure this question is a duplicate of something but it's a pain to find the correct one.

Here is how you can get both results when querying in parallel:

router.get('/userManagement/:id', function(req,res){
  var idNumber = req.params.id;
  Promise.all([
    dbAPI.registeredDevices(true),
    dbAPI.getInfoUser(idNumber)
  ])
  .then(
    ([registeredDevices,userInfo])=>{
      console.log(userInfo);
      console.log(registeredDevices);
      res.render('userManagement.njk', {registeredDevices,userInfo});  
    }
  )
  .catch(
    err=>{
      console.warn("something went wrong:",err);
      res.status(500).send(err);
    }
  );
});

If you want getInfoUser to wait for registeredDevices to finish it'll look like this:

router.get('/userManagement/:id', function(req,res){
  var idNumber = req.params.id;
  dbAPI.registeredDevices(true)
  .then(
    registeredDevices=>
      dbAPI.getInfoUser(idNumber)
      .then(
        ret=>[registeredDevices,ret]
      )
  )
  .then(
    ([registeredDevices,userInfo])=>{
      console.log(userInfo);
      console.log(registeredDevices);
      res.render('userManagement.njk', {registeredDevices, userInfo});
    }
  )
  .catch(
    err=>{
      console.warn("something went wrong:",err);
      res.status(500).send(err);
    }
  )
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM