gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 03:09:36 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com