๐ ์์ ์ฉ ์๋ฒ ์์ฒญ
๊ฒฝ๊ธฐ ๊ฒฐ๊ณผ
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}
Fetch API
- Web API์์ ์ ๊ณตํ๋ ๊ธฐ๋ฅ - ์ฆ ๋ธ๋ผ์ฐ์ ์์ ์ ๊ณต
- ๋คํธ์ํฌ๋ก๋ถํฐ ๋ฆฌ์์ค๋ฅผ ๋ฐ์์ค๊ธฐ ์ํ ๋ค์ํ๊ณ ๊ฐ๋ ฅํ ๊ธฐ๋ฅ๋ค ์ ๊ณต
- ๐ MDN ๋ฌธ์ ๋ณด๊ธฐ
- ๋ณด๋ค ์ค๋๋ ๋ฐฉ๋ฒ: ๐ XMLHttpRequest
fetch ๋ฉ์๋
- ๋คํธ์ํฌ ํต์ ์ผ๋ก ์๊ฒฉ์ ์์ฒญ์ ๋ณด๋ด๊ณ ๋ต์ ๋ฐ์์ค๋ ํ๋ก๋ฏธ์ค๋ฅผ ๋ฐํ
- ๐ MDN ๋ฌธ์ ๋ณด๊ธฐ
// ๐ก ๊ฒฐ๊ณผ๊ฐ Promise์ ์ธ์คํด์ค์ ํ์ธ
console.log(
);
.then(response => {
console.log(response);
return response;
})
.then(response => response.json())
.then(console.log);
๋ฐํ๋๋ ๊ฒฐ๊ณผ ( response )
- ์์ฒญ์ ๊ฒฐ๊ณผ์ ๋ํ ์ ๋ณด๋ค์ ๋ด์ ๊ฐ์ฒด
- json ๋ฉ์๋ - ๊ฒฐ๊ณผ์ body๋ก ๋ฐ์ ํ
์คํธ๋ฅผ JSON ๊ฐ์ฒด๋ก ๋ณํํ์ฌ ๋ฐํ
์ฃผ์ ๋ฑ์ด ์๋ชป๋ ๊ฒฝ์ฐ ๋ฑ ์๋ฌ์ํฉ์ catch์์ ์ฒ๋ฆฌ
fetch('https://WRONG-ADDRESS')
.then(response => response.json())
.then(console.log)
.catch(msg => {
console.error(`๐ณ ์๋ฌ ๋ฐ์: ${msg}`)
})
.finally(() => {
console.log('- - ํต์ ์ข
๋ฃ - -')
})
์์ ์ ๊ฒฐ๊ณผ๋ค ๋ฏธ๋ฆฌ๋ณด๊ธฐ
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);
});
๐ ์ฐ์ fetching ์์
- ๊ฒฝ๊ธฐ ๊ฒฐ๊ณผ๋ฅผ ๋ฐ์์จ ๋ค 1๋ฑ ์ฃผ์ ์ ํ
- ํด๋น ์ฃผ์์ ์์ธ์ ๋ณด ๋ฐ์์จ ๋ค ํ๊ต ์ฝ๋ ์ถ์ถ
- ํด๋น ํ๊ต์ ์ ๋ณด ๋ฐ์์ค๊ธฐ
1. ํ๋ก๋ฏธ์ค ํํ๋ก ๊ตฌํ
โ
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);
2. async, await์ผ๋ก ๊ตฌํ
โ
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();