1

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

Tomasz Mularczyk
  • 34,501
  • 19
  • 112
  • 166
shjnlee
  • 221
  • 2
  • 6
  • 20
  • Possible duplicate of [How do I access previous promise results in a .then() chain?](https://stackoverflow.com/questions/28250680/how-do-i-access-previous-promise-results-in-a-then-chain) – HMR Feb 13 '18 at 05:08

1 Answers1

2

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);
    }
  )
});
HMR
  • 37,593
  • 24
  • 91
  • 160
  • it works!!! Thanks a lot. One last question before I close this thread. Do you know if it's possible to render (send) 2 object to client side? Like, could I possibly call res.render('userManagement.njk', {obj: ret, obj2: registeredDevices}); Or should I concatenate 2 JSON into one and render it (as obj)? – shjnlee Feb 13 '18 at 08:53
  • @shjnlee Doesn't matter either way. Maybe with `{registeredDevices,userInfo}` You have to rename `ret` to `userInfo` I updated the answer accordingly. – HMR Feb 13 '18 at 10:12