javascript로 요청을 하는 새로운 방식
프로미스를 지원
fetch함수는 프로미스를 반환
then과 catch 사용 가능하다
const url = "https://swapi.dev/api/people/1/";
//fetch 함수를 사용
const req = fetch(url);
req
//fetch(url)은 promise를 반환하니 then을 사용해서 resolve 됐을 때 return된 값을 가져옴
.then(res=>console.log(res))
//res의 값
Response {
size: 0,
[Symbol(Body internals)]: {
body: PassThrough {
_readableState: [ReadableState],
_events: [Object: null prototype],
_eventsCount: 5,
_maxListeners: undefined,
_writableState: [WritableState],
allowHalfOpen: true,
[Symbol(kCapture)]: false,
[Symbol(kCallback)]: null
},
stream: PassThrough {
_readableState: [ReadableState],
_events: [Object: null prototype],
_eventsCount: 5,
_maxListeners: undefined,
_writableState: [WritableState],
allowHalfOpen: true,
[Symbol(kCapture)]: false,
[Symbol(kCallback)]: null
},
boundary: null,
disturbed: false,
error: null
},
[Symbol(Response internals)]: {
type: 'default',
url: 'https://swapi.dev/api/people/1/',
status: 200,
statusText: 'OK',
headers: {
allow: 'GET, HEAD, OPTIONS',
connection: 'close',
'content-type': 'application/json',
date: 'Thu, 24 Nov 2022 09:04:57 GMT',
etag: '"ee398610435c328f4d0a4e1b0d2f7bbc"',
server: 'nginx/1.16.1',
'strict-transport-security': 'max-age=15768000',
'transfer-encoding': 'chunked',
vary: 'Accept, Cookie',
'x-frame-options': 'SAMEORIGIN'
},
counter: 0,
highWaterMark: 16384
}
}
req
//fetch(url)은 promise를 반환하니 then을 사용해서 resolve 됐을 때 return된 값을 가져옴
.then(res=>{
console.log(res)
//JSON.parse()와 비슷한 메소드 하지만 res.json()은 promise를 반환 그래서 then 사용
//우리가 필요한 정보들을 받아와서 object로 만들어줌
//우리가 필요한 정보들은 data에 들어있음
// res.json()값을 콘솔에 찍어보면 ->값 나옴 Promise { <pending> }
// res.json().then(data=>console.log(data)) //object로 parse된 json 정보가 data
// console.log(data); res.json().then(()=>{여기에서만 사용 가능함}) 밖에서 참조 못함
return res.json();
})
.then(data=>{
console.log('첫번째 요청 성공')
console.log(data)
//중첩없이 두번째 요청을 하기 위해서 return해줌
return fetch("https://swapi.dev/api/people/2/")
})
.then(res=>{
return res.json();
})
.then((data=>{
console.log('두번째 요청 성공');
console.log(data)
}))
.catch(e=>console.log('err', e))
//비동기함수로 만들어보기
const loadStarWrarsPeople = async ()=>{
try{
const res = await fetch(url);
const data = await res.json();
console.log(data);
const res2 = await fetch("https://swapi.dev/api/people/2/");
const data2 = await res2.json();
console.log(data2);
}catch(e){
console.log(e)
}
}
loadStarWrarsPeople();