繁体   English   中英

如何从封装函数处理Promise

[英]How to handle a Promise from an encapsulated function

这是我一直在努力理解的一个概念:我有一个服务,用于封装Firestore DB调用。 在此类中,我有一个向集合添加文档的方法:

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)
    });
}

如您所见,我能够在服务类本身中处理Promise。 我的问题是:当我从另一个类调用函数时,如何处理该结果? 看:

placeOrder() {
  let order = new Order(this.userProvider.getUser(), this.cart.getItems());
  this.orderService.createOrder(order);
}

我想做的是

this.orderService.createOrder(order).then(res => {})。catch(err => {});

我该如何实现?

只要记住, 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 => {});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM