Angular 等待2种方法完成第6步
我有两种方法,它们使用服务逻辑中提供的REST请求返回两个不同的数组:Angular 等待2种方法完成第6步,angular,typescript,wait,sequential,subscribe,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
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
Promise.all([
firstMethod(key1),
seondMethod(key2),
]).then(value => thirdMethod());
使用承诺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());
在这种情况下,如何返回承诺?您可以执行firstMethod():Promise
并在finction中返回数据