如何解决使用Axios在两个地方点击错误消息
我们将所有api调用都包含在一个api.js文件中,该文件如下所示:
import { axiosClient as axios } from 'Utils';
export const urls = {
getReceiptData: '/purchase/getReceiptData',processPurchase: '/purchase/process-purchase',};
export const getReceiptData = () => axios.get(urls.getReceiptData)
.then(({ data }) => data);
export const purchaseStatus = purchaseId => axios.get(urls.purchaseStatus.replace('$1',purchaseId))
.then(({ data }) => data);
但是,我们希望开始将所有错误消息记录到New Relic,同时不破坏功能。
我最初的反应是在此文件中接收错误消息并在此处进行处理,如下所示:
export const purchaseStatus = purchaseId => axios.get(urls.purchaseStatus.replace('$1',purchaseId))
.then(({ data }) => data,error => newrelic.noticeError(error););
但是从循环调用api.js文件时,我无法获得相同的功能:
pollPurchase = purchaseId => new Promise(resolve => setTimeout(resolve,1000))
.then(() => api.purchaseStatus(purchaseId))
.then((response) => {
if (response.state === 'COMPLETED') {
return true;
}
return this.pollPurchase(purchaseId);
});
似乎打破了循环。 有人对如何做到这一点有建议吗?
解决方法
Axios使用promise模式而不是回调模式,因此请尝试使用
export const purchaseStatus = purchaseId =>
axios.get(urls.purchaseStatus.replace('$1',purchaseId))
.then(({ data }) => data)
.catch(error => {
newrelic.noticeError(error);
return Promise.reject(error);
});
它应该像您尝试传递.then的解决方案那样工作,但是它仅接受第一个,而忽略第二个。
并将pollPurchase方法更新为
pollPurchase = purchaseId => new Promise(resolve => setTimeout(resolve,1000))
.then(() => api.purchaseStatus(purchaseId))
.then((response) => {
if (response.state === 'COMPLETED') {
return true;
}
return this.pollPurchase(purchaseId);
}).catch(console.error)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。