0

I have method callServer which returns a promise. Basically it call the backend service and provides the data. Now in the next method getAccountAndRelatedContacts , I am first getting the accounts adn then the related contacts. So I will have to call the server 2 times. Now I want to understand what is the best way to implement the getAccountandRelatedContacts method keeping in mind that not only the data but also the error should propagate back.

var callServer = function(query){
  return new Promise(function(resolve,reject){
    if(query){
      resolve('Some result'+ query);
    }else {
      reject('inside the resolve');
    }
  })
}

Implementation Method 1:

var getAccountAndRelatedContacts = function(){
  return callServer('Select * from Account')
    .then(function(res){ 
      return callServer('select * from Contact where Account.Id = '+res.Id)
   })
}

Implementation Method 2 :

var getAccountAndRelatedContacts = function(){
return new Promise(function(resolve, reject){
  callServer('Select * from Account')
    .then(function(res){ 
      return callServer('select * from Contact where Account.Id = '+res.Id)
   }).then(function(res){
      resolve(res);
   }).catch(function(err){
      reject(err);
   })
  });
}

Finally calling the method:

//actual Call
getAccountAndRelatedContacts().then(function(results){
  console.log(results);
})
Sam
  • 1,311
  • 2
  • 23
  • 47

0 Answers0