Search code examples
angulartypescriptwaitsequentialsubscribe

Wait for 2 methods to complete Angular 6


I have two methods that return two different arrays using REST requests provided in services logic:

 cartItemNodes: TreeNode[] = [];
 cartGroupNodes: TreeNode[] = [];

 getCartItems(){
  //subscribe to service observable filling the array 
  return this.cartItemNodes;
}

 getCartGroups(){
  //subscribe to service observable filling the array 
  return this.cartGroupNodes;
}

How can I build a third method

getCartFinalNodes()

which waits until the first two are completed and then combines their results into a single array?

getCartFinalNodes(){
//wait for first 2 methods
return this.cartItemNodes.concat(this.cartGroupNodes);
}

Solution

  • firstly return promises from your two methods then use Promise.all like following

      Promise.all([
       firstMethod(key1),
       seondMethod(key2),
      ]).then(value => thirdMethod());