1) 我有一个具体的实现,我想遵守 DRY 原则。 两种方法的结构几乎完全相同。我想知道这是否是一种不重复实现的方法:
addCardToExistingCustomer(cardDetail){
PaymentUtil.stripeCreateCardToken(cardDetail).then((cardTokenResult)=>{
if(cardTokenResult.error){
console.log("There was an error with the card!");
} else {
PaymentUtil.addCardToExistingCustomer(cardTokenResult.id).then((card) =>{
});
}
});
}
addCardToNewCustomer(cardDetail){
this.stripeCreateCardToken(cardDetail).then((cardTokenResult)=>{
if(cardTokenResult.error){
console.log("There was an error with the card!");
} else {
console.log("Successfully created card token");
PaymentUtil.stripeCreateCustomer(cardTokenResult.id)
}
});
}
2)这是链式 promise 的最佳方式吗?具体来说,您应该如何处理链中 promise 的异常,这些异常不是链的最后一个元素。
例如, promise getStripeCustomerId
被拒绝。你应该如何处理拒绝。
addCardToExistingCustomer(cardTokenResultId){
return this.getStripeCustomerId(userDetail).then((customerId) => {
return this.removeAllExistingCards(userDetail).then(()=>{
return Stripe.addCardToCustomer(cardTokenResultId,customerId);
});
});
},
getStripeCustomerId(userDetail){
return FirebaseRESTUtil.getStripeCustomer(userDetail.username)
.then((fbStripe) => (fbStripe.customerId));
},
最佳答案
1-这种方式可以更好..它将使用 promise 链来处理数据。
getCardTokenResult(cardDetail) {
return PaymentUtil.stripeCreateCardToken(cardDetail)
.then((cardTokenResult) => {
if(cardTokenResult.error){
return Promise.reject('There was an error with the card!!');
} else {
return cardTokenResult;
}
})
.catch((error) => console.log(error)):
}
addCardToExistingCustomer(cardDetail){
return getCardTokenResult(cardDetail)
.then((cardTokenResult) => {
PaymentUtil.addCardToExistingCustomer(cardTokenResult.id).then((card) =>{
// do something
});
});
}
addCardToNewCustomer(cardDetail){
return getCardTokenResult(cardDetail)
.then((cardTokenResult) => {
PaymentUtil.stripeCreateCustomer(cardTokenResult.id);
});
}
2-您可以使用catch来获取Promises链上的错误。你可以看看上面的代码。我添加了 catch 以获取 cardtokenresult 错误。您可以在链上继续以相同的方式获取其他错误。
关于javascript - React Native DRY Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38838475/