Search code examples
javascriptnode.jspromisemiddleware

Promise middleware in node js callback functions how to use multiple then?


Am a newby in node js, Am using Promise middleware in node js. But I didn't find its documentation useful for me and unable to understand how to use two callbacks in one request or how should use multiple then. Please help me thanks.

Here is my code

//get application types
var p1 = new Promise(function(resolve, reject) {
  console.log("in p1");
  var url = tURL+'applicationType/getAll'
  var args = {
    headers:{"AuthKey": req.session.name}
  };
  client.get(url, args, function(data,response) {
      console.log(data, "in get all app type req");
      if(data.status == "success"){
        return resolve(data);
      }
      else{
        reject ("unamble to get data!")
      }
  });
});

p1.then(function(data) {
  console.log(data.response.applicationType, "in p1 then", data)
  //load page after data
  res.render('app', {
    message: req.session.name,
    uName: "THE MECHANIC",
    applist: data.response.applicationType
  });
},function(reason) {
  console.log(reason, "reason in not then"); // Error!
});



//get all application
var p2 = new Promise(function(resolve, reject){
  console.log("in p2");
  var url = tURL+'applications'
  var args = {
    headers:{"AuthKey": req.session.name}
  };
  client.get(url, args, function(data,response) {
      console.log(data, "in get app req");
      if(data.status == "success"){
        return resolve(data);
      }
      else{
        reject ("unamble to get data!")
      }
  });
});

p2.then(function(data) {
  console.log(data.response, "in p2 then", data)
  //load page after data
  res.render('app', {
    appList: data.response
  });

},function(reason) {
  console.log(reason, "reason in not p2"); // Error!
});

Solutions am looking for 1. I have to send data on page after both request complete. 2. How can I manage response in object and send it to page by using render or any alternative?


Solution

  • my first advice would be to find a way to promisify client.get in a native fashion, I am not sure what lib it represent, and it is not following node-style callback as fun(err, data), that aside, I am assuming, you have a single request to your server, you carry multiple requests to something else, then bundle up all their responses and respond to the requester right?

    I would restructure the code like

    function pGet(url, args){
      return new Promise(function(resolve, reject){
        client.get(url, args, function(data, response){
          if(data.status === 'success') resolve(data);
          else reject('unable to get data');
        });
      });
    }
    
    router.get('/api/someAPI', function(req, res, next){
      var resultJSON = {
        message: req.session.name,
        uName: "THE MECHANIC"
      }, args = { headers:{"AuthKey": req.session.name} },
      p1, p2;
    
      p1 = pGet(tURL+'applicationType/getAll', args)
        .then(function(data){
          resultJSON.applist = data.response.applicationType;
        }).catch(console.log.bind(console));
    
      p2 = pGet(tURL+'applications', args)
        .then(function(data){
          resultJSON.appList = data.response;
        }).catch(console.log.bind(console));
    
      // now we send the response once both of the promises finish
      Promise.all([p1, p2]).then(function(){
        res.render('app', resultJSON); 
      }); // not adding any error handler since both the previous ones should not throw any.
    
    });