[英]Wait for 2 methods to complete Angular 6
我有两种方法可以使用服务逻辑中提供的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,然后使用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());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.