본문 바로가기
Front-End/JavaScript

fetch

by kk님 2023. 10. 31.

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#checking_that_the_fetch_was_successful

 

Using the Fetch API - Web APIs | MDN

The Fetch API provides a JavaScript interface for accessing and manipulating parts of the protocol, such as requests and responses. It also provides a global fetch() method that provides an easy, logical way to fetch resources asynchronously across the net

developer.mozilla.org

 

 

1. await: 프로미스가 처리될 때까지 기다리는 동시다른 작업을 수행하게 하는 키워드.

const API_END_POINT = 'API 주소 입력';

async function fetchData() {
  try {
    const response = await fetch(
      `${API_END_POINT}`,
      {
        headers: {
          "Content-Type": "application/json",
          "x-username": "user",
        },
      }
    );
    if (response.ok) return response.json();
    throw new Error(API_REQUEST_ERROR);
  } catch (error) {
    console.log(error.message);
  }
  console.log("fetchData 함수의 마지막");
}

function tempFunction() {
  console.log("###This is an unrelated with fetch function###");
}


console.log("start");
fetchData();
console.log("mid");
tempFunction();
console.log("end");

[출력 결과]

start
mid
###This is an unrelated function###
end
API_REQUEST_ERROR is not defined
패치데이터 함수의 마지막

 

정리

1. async가 붙은 함수 내부는 await으로 Promise결과를 받을 때까지, (async가 붙은 내부)함수 코드 진행을 중지한다.

2. async와 관련없는 함수는 비동기적으로 진행된다.

이런 느낌?

3. fetch의 결과로 온 response는 Promise의 결과값이다. resolve(결과) reject(결과)

4. return await response.json()을 하면, fetch를 호출한 부분에서 async-await를 붙이지 않아도 된다.

5. 404 또는 500번대 응답 에러는 throw error를 강제로 발생시키지 않는다. 하지만 response.ok값이 false이기 때문에, if(!response.ok) throw new Error()를 해주어야 한다.