Promise fetch API 사용법

김동찬·2021년 7월 28일
0

fetch를 이용해서 네트워크를 요청

네트워크 요청이 비동기 요청의 대표적이라고 할 수 있다.
이번에 배운 내용은 URL로 요청하는 경우를 학습을 하였다.

//예제를 만들어 보았다. 
let url = '받는 네트워크 url'
fetch(url)
.then(response => response.json())
.then(json =>console.log(json))

링크텍스트

Chaining


var newsURL='http://localhost:5000/data/latestNews';
var weatherURL = 'http://localhost:5000/data/weather';
function test1(){
let obj ={};
return fetch(newsURL)
.then((data)=>data.json())
.then(json =>{
    obj['news']= json.data
    return fetch(weatherURL)
  })
  .then((data)=>data.json())
  .then(json =>{
    obj['weather']=json
    return obj
  })
}

스프린트를 하면서 작성했던 코드를 정리를 해보았다.
페어분들과 작성한 코드들을 비교해보니깐 확실히 여러가지 구성으로 구현이 되었다.
가독성이 중요하니
제일 보기 좋았던 코드를 정리해봅니다.

Promise all


function test2() {
 
  let obj = {};
  const news = fetch(newsURL)
  .then(data => data.json())
  const weather = fetch(weatherURL)
  .then(data =>data.json())

  return Promise.all([news, weather]) // Promise.all 를 이용해서 구현
  .then(([json1, json2])=>{
    obj['news'] = json1.data
    obj['weather'] = json2
    return obj
  })
}

async Await

async function test3() {
  
  const news = await fetch(newsURL)
  .then(data => data.json())
  const weather = await fetch(weatherURL)
  .then(data =>data.json())

  return {news: news.data,  weather : weather}
}
profile
프론트엔드 지망 개발공부를 하는 김동찬입니다 ^^7 코드스테이츠

0개의 댓글