[英]How to handle a Promise from an encapsulated function
This is a concept I've been struggling to understand: I have a service in which I'm encapsulating my Firestore DB calls. 这是我一直在努力理解的一个概念:我有一个服务,用于封装Firestore DB调用。 In this class I have a method to add a doc to a collection: 在此类中,我有一个向集合添加文档的方法:
createOrder(order: Order) {
let o = {user: order.user, total: order.total, items: this.parseItems(order.items), uid: order.uid};
this.ordersRef.add(o).then(res => {
console.log(res)
}).catch(err => {
console.log(err)
});
}
As you can see, I'm able to handle the promise within the service class itself. 如您所见,我能够在服务类本身中处理Promise。 My question is: how can I handle that result when I call the function from another class? 我的问题是:当我从另一个类调用函数时,如何处理该结果? Look: 看:
placeOrder() {
let order = new Order(this.userProvider.getUser(), this.cart.getItems());
this.orderService.createOrder(order);
}
What I want to do is something like 我想做的是
this.orderService.createOrder(order).then(res => {}).catch(err => {}); this.orderService.createOrder(order).then(res => {})。catch(err => {});
How can I achieve that? 我该如何实现?
Just remember that then()
also returns a promise. 只要记住, then()
也会返回一个承诺。 So you can return the whole chain and still have a promise to call then()
on: 因此,您可以返回整个链,并且仍然可以在以下情况下调用then()
:
createOrder(order: Order) {
let o = {user: order.user, total: order.total, items:
this.parseItems(order.items), uid: order.uid};
// return the promise to the caller
return this.ordersRef.add(o).then(res => {
console.log(res)
// you only need this then() if you have further processing
// that you don't want the caller to do
// make sure you return something here to pass
// as a value for the next then
return res
})
/* let the caller catch errors unless you need to process before the called get it.
.catch(err => {
console.log(err)
});
*/
}
Now this should work fine: 现在,这应该可以正常工作:
this.orderService.createOrder(order)
.then(res => {})
.catch(err => {});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.