Reputation: 2323
This is a concept I've been struggling to understand: I have a service in which I'm encapsulating my Firestore DB calls. 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. 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 => {});
How can I achieve that?
Upvotes: 0
Views: 119
Reputation: 92440
Just remember that then()
also returns a promise. So you can return the whole chain and still have a promise to call then()
on:
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 => {});
Upvotes: 1