简体   繁体   中英

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. 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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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