等待2种方法来完成Angular 6

时间:2018-09-03 10:41:52

标签: angular typescript wait sequential subscribe

我有两种使用服务逻辑中提供的REST请求返回两个不同数组的方法:

 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;
}

如何构建第三种方法

  

getCartFinalNodes()

哪个会一直等到前两个 完成,然后将其结果合并到一个数组中?

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

2 个答案:

答案 0 :(得分:3)

首先通过两种方法返回承诺,然后像下面一样使用Promise.all

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

答案 1 :(得分:2)

使用Promise API:

getCartItems() {
    return new Promise((resolve, reject) => {
        resolve(this.cartItemNodes);
    });
}

getCartGroups() {
    return new Promise((resolve, reject) => {
        resolve(this.cartGroupNodes);
    });
}

Promise.all([
    this.getCartItems(),
    this.getCartGroups(),
    ]).then(value => this.getCartFinalNodes());