[英]Axios - multiple requests for the same resource
I'm creating an app where in one page, I have two components requesting the same http resource. 我正在创建一个应用程序,其中在一个页面中,我有两个组件请求相同的http资源。 In this case I'm using axios and here's one example: 在这种情况下,我使用axios,这是一个示例:
axios.get('/api/shift/type')
.then(
(response) => {
self.shiftTypes = response.data;
success(response.data)
},
(response) => {
error(response)
}
);
The issue lies in them requesting it almost at the same time. 问题在于他们几乎同时要求它。 If Component A makes the request at the same time as Component B, 2 request calls are made and they'll get the same data. 如果组件A与组件B同时发出请求,则将进行2次请求调用,它们将获得相同的数据。 Is there a way to check if axios currently has an unresolved promise and return the result to both components once the request is resolved? 有没有一种方法可以检查axios当前是否有未解决的Promise,并在解决请求后将结果返回给两个组件?
Not sure if it helps but the app is being built using the vue framework 不确定是否有帮助,但是正在使用vue框架构建应用程序
Thanks 谢谢
EDIT: I tried storing the promise in memory but Component B never gets the response 编辑:我试图将诺言存储在内存中,但组件B永远不会收到响应
getShiftTypes(success, error = this.handleError, force = false) {
if (this.shiftTypes && !force) {
return Promise.resolve(this.shiftTypes);
}
if (this.getShiftTypesPromise instanceof Promise && !force) { return this.getShiftTypesPromise; }
let self = this;
this.getShiftTypesPromise = axios.get('/api/shift/type')
.then(
(response) => {
self.shiftTypes = response.data;
self.getShiftTypesPromise = null;
success(response.data)
},
(response) => {
error(response)
}
);
return this.getShiftTypesPromise;
}
Consider using a cache: 考虑使用缓存:
let types = { lastFetchedMs: 0, data: [] }
async function getTypes() {
const now = Date.now();
// If the cache is more than 10 seconds old
if(types.lastFetchedMs <= now - 10000) {
types.lastFetchedMs = now;
types.data = await axios.get('/api/shift/type');
}
return types.data;
}
while(types.data.length === 0) {
await getTypes();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.