AbortController

개발 자료 끄적끄적·2024년 1월 16일

webapi

목록 보기
1/1

'AbortController'는 비동기 작업을 취소하거나 중단할 수 있는 기능을 제공하는 Web API 중 하나.

사용법

  1. AbortController 생성:
const abortController = new AbortController();
  1. AbortController 얻기:
const abortSignal = abortController.signal;
  1. 비동기 작업에 Signal 적용:
  • fetch를 사용하는 경우:
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);
    }
  });
  • XMLHttpRequest를 사용하는 경우:
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();
  1. 작업 취소
abortController.abort();

AbortController를 왜 사용하는지

  • 사용할 경우
    - 비동기 작업을 시작하고, 작업 중에 abortController.abort()를 호출하여 작업을 중단할 수 있다.
    - 중단된 작업에 대한 AbortError를 캐치할 수 있어, 중단된 작업에 대한 추가 로직을 수행할 수 있다.
  • 사용하지 않을 경우
    - 작업을 시작하면 중간에 중단하기 어렵거나 복잡할 수 있다.
    - 작업이 중간에 중단되더라도 해당 작업이 이미 완료되고 결과가 사용되었을 수 있다.

AbortController를 사용하면 특히 사용자가 요청을 취소하거나 페이지를 떠나는 등의 상황에서 비동기 작업을 중단하는 데 유용하며, 이를 통해 불필요한 네트워크 요청이나 리소스 사용을 방지하고, 성능을 향상시킬 수 있다.

profile
지금은 비공개로 개발 자료 기록중입니다!

0개의 댓글