'AbortController'는 비동기 작업을 취소하거나 중단할 수 있는 기능을 제공하는 Web API 중 하나.
const abortController = new AbortController();
const abortSignal = abortController.signal;
fetch(url, { signal: abortSignal })
.then(response => response.json())
.then(data => console.log(data))
.catch(error => {
if (error.name === 'AbortError') {
console.log('Request was aborted');
} else {
console.error('Error during fetch', error);
}
});
const xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
console.log(xhr.responseText);
} else {
console.error('Error during XMLHttpRequest', xhr.statusText);
}
}
};
xhr.onerror = function (error) {
console.error('Error during XMLHttpRequest', error);
};
xhr.withCredentials = true; // if needed
xhr.send();
abortController.abort();
AbortController를 사용하면 특히 사용자가 요청을 취소하거나 페이지를 떠나는 등의 상황에서 비동기 작업을 중단하는 데 유용하며, 이를 통해 불필요한 네트워크 요청이나 리소스 사용을 방지하고, 성능을 향상시킬 수 있다.