์ƒ์„ธ ์ปจํ…์ธ 

๋ณธ๋ฌธ ์ œ๋ชฉ

[์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ]fetch ๋„คํŠธ์›Œํฌ ๋น„๋™๊ธฐ

์นดํ…Œ๊ณ ๋ฆฌ ์—†์Œ

by esoesmio 2023. 5. 18. 02:21

๋ณธ๋ฌธ

https://showcases.yalco.kr/javascript/mockserver/race-result

 

https://showcases.yalco.kr/javascript/mockserver/runners/{1~5}

 

https://showcases.yalco.kr/javascript/mockserver/schools/{1~3}

 

// ๐Ÿ’ก ๊ฒฐ๊ณผ๊ฐ€ Promise์˜ ์ธ์Šคํ„ด์Šค์ž„ ํ™•์ธ
console.log(
    fetch('https://showcases.yalco.kr/javascript/mockserver/race-result')
);

fetch('https://showcases.yalco.kr/javascript/mockserver/race-result')
    .then(response => {
        console.log(response);
        return response;
    })
    .then(response => response.json())
    .then(console.log);

 

 

const SERVER_URL = 'https://showcases.yalco.kr/javascript/mockserver/';

fetch(SERVER_URL + 'race-result')
    .then(response => response.json())
    .then(console.log)
    .catch(console.error);

[1, 2, 3, 4, 5].forEach(item => {
    fetch(`${SERVER_URL}runners/${item}`)
        .then(response => response.json())
        .then(console.log)
        .catch(console.error);
});

[1, 2, 3].forEach(item => {
    fetch(`${SERVER_URL}schools/${item}`)
        .then(response => response.json())
        .then(console.log)
        .catch(console.error);
});

 

  1. ๊ฒฝ๊ธฐ ๊ฒฐ๊ณผ๋ฅผ ๋ฐ›์•„์˜จ ๋’ค 1๋“ฑ ์ฃผ์ž ์„ ํƒ
  2. ํ•ด๋‹น ์ฃผ์ž์˜ ์ƒ์„ธ์ •๋ณด ๋ฐ›์•„์˜จ ๋’ค ํ•™๊ต ์ฝ”๋“œ ์ถ”์ถœ
  3. ํ•ด๋‹น ํ•™๊ต์˜ ์ •๋ณด ๋ฐ›์•„์˜ค๊ธฐ

 

ํ”„๋กœ๋ฏธ์Šค๋กœ ๊ตฌํ˜„

 

 

const SERVER_URL = 'https://showcases.yalco.kr/javascript/mockserver/';

fetch(SERVER_URL + 'race-result')
    .then(result => result.json())
    .then(arry => {
        return arry.sort((a, b) => {
            return a.record - b.record
        })[0].runner_idx
    })
    .then(winnerIdx => {
        return fetch(`${SERVER_URL}runners/${winnerIdx}`)
    })
    .then(result => result.json())
    .then(({school_idx}) => school_idx)
    .then(schoolIdx => {
        return fetch(`${SERVER_URL}schools/${schoolIdx}`)
    })
    .then(result => result.json())
    .then(console.log)
    .catch(console.error);

 

 

async wait๋กœ ๊ตฌํ˜„

 

 

const SERVER_URL = 'https://showcases.yalco.kr/javascript/mockserver/';

async function getWinnersSchool () {

    const raceResult = await fetch(SERVER_URL + 'race-result')
        .then(result => result.json());

    const winnerIdx = raceResult
        .sort((a, b) => {
            return a.record - b.record
        })[0].runner_idx;

    const winnerInfo = await fetch(`${SERVER_URL}runners/${winnerIdx}`)
        .then(result => result.json());

    const schoolIdx = winnerInfo.school_idx;

    const schoolInfo = await fetch(`${SERVER_URL}schools/${schoolIdx}`)
        .then(result => result.json());

    console.log(schoolInfo);
}

getWinnersSchool();

๋Œ“๊ธ€ ์˜์—ญ