axios 요청을 취소하는 방법을 처음으로 알게되었다.
어떠한 request가 유효하지 않을때 아래의 방법으로 요청을 취소할 수 있다.
예를 들어 검색 기능 구현 중 검색어가 짧은 시간 내에 여러번 변경되어 요청될 경우
이전의 요청은 보낼 필요가 없으므로 취소하면 리소스를 낭비하지 않을 수 있다.
axios 공식문서에 나와있는 바와 같이 두 가지 cancel 방법이 있다.
- signal : abortController
- cancelToken (deprecated)
https://axios-http.com/docs/cancellation
Cancellation | Axios Docs
Cancellation Cancelling requests Setting the timeout property in an axios call handles response related timeouts. In some cases (e.g. network connection becomes unavailable) an axios call would benefit from cancelling the connection early. Without cancella
axios-http.com
두가지 방법 모두 코드 흐름은 비슷하다.
axios 요청에 옵션으로 signal 또는 cancleToken 을 전달해준다.
원하는 시점에 abort() 또는 cancel() 호출하여 api request를 중단할 수 있다.
1. abortController
const controller = new AbortController();
axios.get('/foo/bar', {
signal: controller.signal
}).then(function(response) {
//...
});
// cancel the request
controller.abort()
2. cancelToken
const CancelToken = axios.CancelToken;
const source = CancelToken.source();
axios.get('/user/12345', {
cancelToken: source.token
}).catch(function (thrown) {
if (axios.isCancel(thrown)) {
console.log('Request canceled', thrown.message);
} else {
// handle error
}
});
source.cancel('Operation canceled by the user.');
'개발 공부 일지 > JavaScript' 카테고리의 다른 글
| [프로그래머스] 기사 단원의 무기 (0) | 2025.04.30 |
|---|---|
| [프로그래머스] 캐시 (1) | 2025.04.25 |
| [프로그래머스] 피로도 (0) | 2025.04.21 |
| button 태그는 새 탭에서 열 수 없다 (0) | 2025.04.18 |
| 유클리드 호제법 - 최대 공약수 (0) | 2025.04.08 |