The Web Developer 부트캠프 2022

Fetch API

거위발바닥 2022. 9. 26. 15:29
fetch("https://swapi.dev/api/people/1")  // Promise 반환 
    .then(res => {
        console.log('RESOLVE!', res) // resolve시 log가 뜨고 반환된 res가 나옴
    })
    .catch(e => {
        console.log("ERROR!", e)
    })

하지만 res 값에선 우리가 원하는 정보가 api에서 오지 않았는데, 그 이유는 반환된 res가 바로 실행되어 들어가지 않음

res.json().then(data => console.log('JSON DONE', data))

이걸 추가해주면 반환된 res를 json으로 읽어 data로 출력한다

fetch("https://swapi.dev/api/people/1")  // Promise 반환 
    .then(res => { // 반환된 promise가 전달되어 resolve나 reject됨
        console.log('RESOLVE!', res) // resolve시 log가 뜨고 반환된 res가 나옴
        return res.json() // res 응답 객체에 대해 res.json을 호출 
    })
    .then(data => {
        console.log(data)
    })
    .catch(e => {
        console.log("ERROR!", e)
    })

리팩토링

fetch("https://swapi.dev/api/people/1")  // Promise 반환 
    .then(res => { // 반환된 promise가 전달되어 resolve나 reject됨
        console.log('RESOLVE!', res) // resolve시 log가 뜨고 반환된 res가 나옴
        return res.json() // res 응답 객체에 대해 res.json을 호출 
    })
    .then(data => {
        console.log(data) // 요청된 데이터를 보기 위해서 (res.json)
        return fetch("https://swapi.dev/api/people/2")
    })
    // 두번째
    .then(res => {
        console.log("SECOND");
        return res.json();
    })
    .then(data => {
        console.log(data)
        return fetch("https://swapi.dev/api/people/3")
    })
    // 세번째
    .then(res => {
        console.log("THIRD");
        return res.json();
    })
    .then(data => {
        console.log(data);
    })
    .catch(e => {
        console.log("ERROR!", e);
    })

위 코드는 연속적이기 때문에 people/1 이 실행되지 않으면 나머지는 실행도 안됨

const loadStarWarsPeople = async () => {
    try {
        const res = await fetch("https://swapi.dev/api/people/1")
        const data = await res.json();
        console.log(data);
        // 두번째
        const res2 = await fetch("https://swapi.dev/api/people/2")
        const data2 = await res.json();
        console.log(data2);
    } catch (e) {
        console.log("ERROR!!!", e);
    }
}
loadStarWarsPeople();

비동기함수로 처리해서 훨씬 깔끔하게 가능

'The Web Developer 부트캠프 2022' 카테고리의 다른 글

API Header  (0) 2022.09.26
AXIOS  (0) 2022.09.26
JSON parese, stringify, API 요청 종류, Http statue  (0) 2022.09.26
JS Try, catch 를 이용한 async 문제 해결  (0) 2022.09.25
JS 비동기 async 함수, await  (0) 2022.09.25