[ES6+] promise의 사용


fetch 는 promise를 return한다

fetch("https://google.com")
.then(response => console.log(response))
.catch(e => console.log(`${e}`));

동작하지는 않지만(구글이 막아놈), 이게 프로미스라는건 알 수 있다



c.f)fetch를 하면 body에 ReadableStream이라고 되어있는데, 스트림은 js에서 바이트를 의미한다

response자체가 promise를 리턴하는 함수를 포함하고 있다

fetch("https://google.com")
.then(response => console.log(response.text())
.catch(e => console.log(`${e}`));

잠만잠만… 이해가….

fetch로 api를 받아오면 response로 받아오는데, 그 response.text()로 받아오고(여기까지는 이해)

근데 저게 reponse로 불러오는 동시에 promise를 리턴한다고 한다

저 말인즉 .then() 을 또 써주어야한다는 말씀

결국엔 then안의 내용은 response를 text로 만든 내용을 받아올것이다

fetch("https://google.com")
.then(response => console.log(response.text())
.then(potato => console.log(potato))	//변수는 내맘대로
.catch(e => console.log(`${e}`));



fetch("https://yts.am/api/v2/list_movies.json")
.then(response => {
  console.log(response);
  return response.json();
})
.then(json => console.log(json))
.catch(e => console.log(e))

response.json 으로 리턴한 값을 then 이후의 json으로 받아서 콘솔에 찍으면 json만 콘솔에 찍는다

처음의 response는 정말 fetch의 response이고, json으로 받아온건 json만 찍힌다 =)

이번거는 뭐라고 정리하기가 좀 애매하군…..





노마드코더의 ‘ES6의 정석’을 듣고 정리 =)




© 2018. by sora

Powered by sora