Skip to content

Instantly share code, notes, and snippets.

@zlrlo
Last active November 15, 2022 08:58
Show Gist options
  • Select an option

  • Save zlrlo/f47b55fc8678a5137dfd0a78e81d86cc to your computer and use it in GitHub Desktop.

Select an option

Save zlrlo/f47b55fc8678a5137dfd0a78e81d86cc to your computer and use it in GitHub Desktop.
fetch를 통한 요청 중 오래 걸리는 요청일 경우 timeout을 두고 중단이 필요한 경우가 있을 수 있다. 이럴 때 AbortController를 이용해 처리가 가능하다.
async function fetchWithTimeout(resource, options = {}) {
const { timeout = 8000 } = options;
const controller = new AbortController();
const id = setTimeout(() => controller.abort(), timeout);
const response = await fetch(resource, {
...options,
signal: controller.signal
});
clearTimeout(id);
return response;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment