这是我一直在努力理解的概念:我有一项服务,我将我的Firestore数据库调用封装起来。在本课程中,我有一种方法可以将文档添加到集合中:
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)
});
}
如您所见,我能够在服务类本身内处理承诺。我的问题是:当我从另一个类调用该函数时,如何处理该结果?看:
placeOrder() {
let order = new Order(this.userProvider.getUser(), this.cart.getItems());
this.orderService.createOrder(order);
}
我想做的是像
this.orderService.createOrder(order).then(res => {})。catch(err => {});
我怎样才能做到这一点?
答案 0 :(得分:1)
请记住,then()
也会返回一个承诺。因此,您可以返回整个链,并且仍然有权致电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)
});
*/
}
现在这应该可以正常工作:
this.orderService.createOrder(order)
.then(res => {})
.catch(err => {});