반응형
Axios - 동일한 리소스에 대한 여러 요청
한 페이지에 동일한 http 리소스를 요청하는 두 구성 요소가 있는 앱을 만드는 중.이 경우에 나는 공리를 사용하고 있는데, 여기 한 가지 예를 들어보자.
axios.get('/api/shift/type')
.then(
(response) => {
self.shiftTypes = response.data;
success(response.data)
},
(response) => {
error(response)
}
);
문제는 그들이 거의 동시에 그것을 요청하는 데 있다.컴포넌트 A가 컴포넌트 B와 동시에 요청하면 2번의 요청 전화가 걸려와 동일한 데이터를 받게 된다.공리가 현재 미해결 약속을 가지고 있는지 확인하고 요청이 해결되면 결과를 두 구성 요소로 반환할 방법이 있는가?
도움이 될지 모르겠지만 vue 프레임워크를 사용하여 앱을 빌드하고 있음
고마워요.
편집: 약속을 메모리에 저장하려고 했지만 구성 요소 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;
}
캐시 사용 고려:
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();
}
참조URL: https://stackoverflow.com/questions/48368019/axios-multiple-requests-for-the-same-resource
반응형
'Programing' 카테고리의 다른 글
파일 업로드(vuetify) (0) | 2022.03.08 |
---|---|
리액터 v4 페이지 새로 고침이 작동하지 않음 (0) | 2022.03.08 |
Vuejs 정의되지 않은 오류의 속성 '사용'을 읽을 수 없음 (0) | 2022.03.08 |
vue의 형식 지정 - 속성 'validate'가 'Vue | 요소 | 부[] | 요소[]'에 존재하지 않음 (0) | 2022.03.08 |
Python의 모든 기능은 어떻게 작동하는가? (0) | 2022.03.08 |