我有两个方法使用服务逻辑中提供的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);
}
首先从你的两种方法返回承诺,然后像下面一样使用Promise.all
Promise.all([
firstMethod(key1),
seondMethod(key2),
]).then(value => thirdMethod());
使用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());