📚 비동기 복습

Purple·2021년 10월 28일
0

TIL

목록 보기
42/73

📚 비동기 복습...

1. callback사용, promise 사용

delay함수는 콜백을 이용해서 setTimeout을 실행한다.

const delay = (wait, callback) => {
  setTimeout(callback, wait);
}

sleep함수는 Promise를 사용해서 setTimeout을 실행한다.

 const sleep = (wait) => {
   return new Promise((resolve) => {
     setTimeout(resolve, wait);
   });
 }

2. response.json()의 진실

fetch(url)
 .then((response) => response.json()) //메소드 이름은 json이지만, 사실 JSON을 input으로 받아 파싱 후 Promise의 결과(JS object)로 전달한다.
 .then((json) => console.log(json)) // 콘솔에 json을 출력한다
 .catch((error) => console.log(error));//에러가 발생하는 경우 에러를 콘솔에 출력한다.

응답(Response)의 body를 JSON으로 변환 후 파싱한 결과를 다음 Promise로 전달한다!!!

Note that despite the method being named json(), the result is not JSON but is instead of the result of taking JSON as input and parsing it to produce a JavaScript object.
MDN링크

3. Promise hell에 빠지지 않기

  • return을 시켜주면서 then 사용한다.
const printAll = () => {
  printString("A")
  .then(() => {
    return printString("B")
  })
  .then(() => {
    return printString("C")
  })
}
printAll()
  • 그렇지 않으면..callback hell처럼 점점 함수가 hell속으로 빠지는 것을 볼 수 있다. 물론 지금은 3개 밖에 안되서 표시가 확 나진 않지만...
printString("A")
.then (() => {
  printString("B")
  .then (() => {
    printString("C")
  })
})
profile
다시 보면, 더 많은 것들이 보인다.

0개의 댓글