[1일1js] 콜백 문제

Lee Tae-Sung·2021년 10월 20일
0

JS

목록 보기
46/56

https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Promises#the_trouble_with_callbacks

콜백 문제

약속을 통한 개선

피자 주문 문제

이 과정을

그전의 전통적인 callback

chooseToppings(function(toppings) {
  placeOrder(toppings, function(order) {
    collectOrder(order, function(pizza) {
      eatPizza(pizza);
    }, failureCallback);
  }, failureCallback);
}, failureCallback);

promise

chooseToppings()
.then(function(toppings) {
  return placeOrder(toppings);
})
.then(function(order) {
  return collectOrder(order);
})
.then(function(pizza) {
  eatPizza(pizza);
})
.catch(failureCallback);

=> 겹치는게 아니라 한줄로 줄을 설 수 있다.
=> catch는 꿀 빨고 있는게 아니라
=> 언제든지 내려오다가 실패하면 작동된다.

정리하자면

  1. 무슨 일이 일어나고 있는지 보기가 더 쉽다.
  2. .catch가 모든 오류를 처리하기 때문에 단일 블록만 필요하고 메인 스레드를 차단하지 않는다.
  3. 블록 실행이 완료디ㅗ면 새 약속을 반환하기 때문에 여러 비동기 작업을 순서에 맞게 연결할 수 있음

화살표 함수를 쓰면 더 간결해짐

chooseToppings()
.then(toppings =>
  placeOrder(toppings)
)
.then(order =>
  collectOrder(order)
)
.then(pizza =>
  eatPizza(pizza)
)
.catch(failureCallback);
chooseToppings()
.then(toppings => placeOrder(toppings))
.then(order => collectOrder(order))
.then(pizza => eatPizza(pizza))
.catch(failureCallback);
chooseToppings().then(placeOrder).then(collectOrder).then(eatPizza).catch(failureCallback);

=> 심지어 이렇게까지 할 수 있다.

이벤트 리스너와 유사하지만 다른점

  1. 약속은 한 번만 성공하거나 실패. 되돌릴 수 없다.
  2. 나중에 성공/실패 콜백을 추가하면 이벤트가 더 일찍 발생하더라도 올바른 콜백함수 호출

=> 2번은 지금 뭔 소리인지 모르겠다....

profile
긍정적인 에너지를 가진 개발자, 이태성입니다.

0개의 댓글