Fetch API

김혁중·2022년 3월 19일
0

JavaScript

목록 보기
18/23

Fetch API

fetch

문법

  • const fetchResponsePromise = fetch(resource [, init])
  • return A Promise that resolves to a Response object.

의미

Promise를 return하는 함수
1. 비동기적으로 동작하는 함수일 가능성이 매우 높음
2. 두 개의 함수를 사용할 수 있음(정확히 말하면 method)

*** fetch를 사용한 결과가 성공했을 때 ***
RESOLVED, .then()
fetch.then(callback(response)) => response 객체를 return

*** fetch를 사용한 결과가 실패했을 때 ***
REJECTED, .catch()
fetch.catch(callback(reason))

사용

fetch('https://jsonplaceholder.typicode.com/posts')
  .then(function(response) {
    console.log(response.json())
  }) // Promise {<pending>}
  • Promise를 리턴

사용2

fetch('https://jsonplaceholder.typicode.com/posts')
  .then(function(response) {
    return response.json()
  })
  .then(function(myJson) {
    console.log(myJson)
  }) // (100) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
  • JSON -> JavaScript

정리

json 파일을 fetch().then 으로 받으면 => response 파일
fetch().then => return response.json() => promise
fetch().then => return response.json() => .then => JavaScript

profile
Digital Artist가 되고 싶은 초보 개발자

0개의 댓글