【问题标题】:How to handle a Promise from an encapsulated function如何处理来自封装函数的 Promise
【发布时间】:2018-04-10 21:49:31
【问题描述】:

这是一个我一直在努力理解的概念:我有一个服务,我在其中封装了我的 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)
    });
}

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

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

我想要做的是类似的事情

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

我怎样才能做到这一点?

【问题讨论】:

  • 你为什么不能简单地return this.ordersRef.add....
  • 我可能错了,但我认为您需要做的就是返回res 并调用this.orderService...。编辑:或者可能只是后者。
  • @MeirionHughes 就像你和下面的 Mark 所说的那样,谢谢!

标签: javascript angular ionic2 google-cloud-firestore


【解决方案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 => {});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-05
    • 2020-09-20
    • 1970-01-01
    • 2021-11-10
    • 2022-01-21
    • 2019-05-06
    • 2019-10-24
    相关资源
    最近更新 更多