[JS] 비동기 통신을 할 때 fetch

chael_lo·2022년 4월 5일
0

JavaScript

목록 보기
2/2

비동기 통신을 위해 사용할 수 있는 것들은 여러가지가 있다.

  1. XMLHttpRequest - 브라우저 내장 객체
  2. ajax - jquery 이용
  3. fetch - 브라우저 내장 객체

그 중에서 fetch는 브라우저 내장 객체(엄밀하게 말하면 브라우저 window 객체)이면서 http 옵션이 많아서 사용하기 편하다.
개인적으로는 XMLHttpRequest보다도 알아보기도 쉽다.

fetch 파라미터

fetch는 첫번째 파라미터로 url, 두번째 파라미터로는 options 객체를 받는다.

fetch(url, options)
  .then((response) => console.log("response:", response))
  .catch((error) => console.log("error:", error));

fetch options

options으로는 http 방식, http 요청 헤더, http 요청 바디 등을 설정할 수 있다.
response 응답 객체를 통해 상태, 타입 등을 알 수 있다.

//options 예시
let config = {
	method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
}
//url 예시 https://jsonplaceholder.typicode.com/posts
fetch("https://jsonplaceholder.typicode.com/posts", config)
.then((response) => console.log("response:", response))//응답 객체
.catch((error) => console.log("error:", error));

fetch와 json

응답 객체는 json 메서드도 제공한다.

fetch("https://jsonplaceholder.typicode.com/posts")
.then((response) => response.json())//json 값을 리턴
.then((data) => console.log(data));//리턴받은 json 값으로 원하는 처리 가능

async await

fetch 특성상 가끔 원하는 순서대로 동작하지 않을 때가 있다.
그럴 때 순서 보장을 위해 async, await를 사용한다.
await는 async 선언이 된 함수 안에서만 사용이 가능하다.
Promise를 기다렸다가 Promise 값에서 결과값을 추출해준다.
그리고 async를 선언한 함수는 반드시 Promise를 리턴한다.

async와 await 더 알아보기

promise 더 알아보기

//https://ko.javascript.info/async-await에서 예시 참조
async function showAvatar() {
  // JSON 읽기
  let response = await fetch('fetch할 url');
  let user = await response.json();
}
profile
천천히 꾸준히

0개의 댓글