javascript - 如何处理来自封装函数的 Promise

标签 javascript angular ionic2 google-cloud-firestore

这是我一直在努力理解的一个概念:我有一项服务,其中封装了我的 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() 也会返回一个 promise 。因此,您可以返回整个链,并且仍然有一个调用 then() 的 promise :

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

关于javascript - 如何处理来自封装函数的 Promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47006385/

相关文章:

javascript - 如何编写正则表达式来检查特定数量的字符?

Angular 2 ngx-Datatable celltemplate

html - 沿着悬停的 div 上的光标移动文本

angular - 使用组件而不导入

javascript - NodeJs错误v-host中间件

JavaScript 数字疯狂

javascript - Canvas 动画运行不流畅。我能做些什么?

angular - 单击按钮并通过 component - angular 增加数字

Angular 2 数据持久化

android - ionic 构建 android,错误 : spawn EACCES