home강의 홈으로
Section 14. 비동기 프로그래밍
Lesson 5. 네트워크 통신에서의 활용

🌐 예제용 서버 요청

경기 결과

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( 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);

반환되는 결과 ( response )

  • 요청의 결과에 대한 정보들을 담은 객체
  • json 메서드 - 결과의 body로 받은 텍스트를 JSON 객체로 변환하여 반환


주소 등이 잘못된 경우 등 에러상황시 catch에서 처리

fetch('https://WRONG-ADDRESS') .then(response => response.json()) .then(console.log) .catch(msg => { console.error(`😳 에러 발생: ${msg}`) }) .finally(() => { 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); });



🔗 연속 fetching 예제

  1. 경기 결과를 받아온 뒤 1등 주자 선택
  2. 해당 주자의 상세정보 받아온 뒤 학교 코드 추출
  3. 해당 학교의 정보 받아오기


1. 프로미스 형태로 구현

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);

2. async, await으로 구현

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();

🤔얄코에게 질문하기질문은 반.드.시 이리로 보내주세요! ( 강의사이트 질문기능 ✖ )

강의에서 이해가 안 되거나 실습상 문제가 있는 부분,
설명이 잘못되었거나 미흡한 부분을 메일로 알려주세요!

답변드린 뒤 필요할 경우 본 페이지에
관련 내용을 추가/수정하도록 하겠습니다.

이메일 주소
yalco@yalco.kr
메일 제목 (반드시 아래 제목을 붙여넣어주세요!)
[질문] 제대로 파는 자바스크립트 (유료 파트) 14-5

🛑질문 전 필독!!

  • 구글링을 먼저 해 주세요. 들어오는 질문의 절반 이상은 구글에 검색해 보면 1분 이내로 답을 찾을 수 있는 내용들입니다.
  • 오류 메시지가 있을 경우 이를 구글에 복붙해서 검색해보면 대부분 짧은 시간 내 해결방법을 찾을 수 있습니다.
  • 강의 페이지에 추가사항 등 놓친 부분이 없는지 확인해주세요. 자주 들어오는 질문은 페이지에 추가사항으로 업데이트됩니다.
  • "유료파트의 강의페이지는 어디 있나요?" - 각 영상의 시작부분 검은 화면마다 해당 챕터의 강의페이지 링크가 있습니다.
  • 질문을 보내주실 때는 문제가 어떻게 발생했고 어떤 상황인지 등을 구체적으로 적어주세요. 스크린샷을 첨부해주시면 더욱 좋습니다.
🌏 Why not change the world?