[JavaScript] Callback 패턴

Peter·2022년 3월 9일
0

JavaScript

목록 보기
6/9
post-thumbnail

Callback 패턴?

function foo(callback) {
  const a = 10;
  const b = 20;
  callback(a, b);
}

function boo(a, b) {
  return a + b;
}

foo(boo);
  • 콜백은 함수에 인자로 넣어지는 함수
  • 자바스크립트에선 함수 자체가 객체이기 때문에 함수의 인자로 넣어줄 수 있음

Callback을 사용한 비동기 처리

function squareAndCallBack(number) {
  let square;
  setTimeout(() => {
  	square = number * number
  }, 100);
  console.log(square);
}
  
squareAndCallBack(2);
// undefined
  • 자바스크립트는 setTimeout을 기다려주지 않는다 WebAPI를 호출해 task queue로 넘긴다
  • 바로 콘솔로그를 실행하고 setTimeout의 로직을 실행하기 때문에 square는 undefined이다.
function squareAndCallBack(number, callback) {
  setTimeout(() => {
  	const square = number * number
  	callback(square)
  }, 100);
}

function consolePrint(value) {
  console.log(value);
}
  
squareAndCallBack(2, consolePrint);
// 4
  • 위와 같은 비동기 문제를 해결하기 위해 콜백을 사용할 수 있다.
  • setTimeout로직 안에 콜백함수를 넣어주면 로직이 실행된뒤 콜백을 통해 결과를 가지고 무언가를 할 수 있다.

주의할 점

foo(() => {
  bar(() => {
    baz(() => {
      qux(() => {
        quux(() => {
          quuz(() => {
            corge(() => {
              grault(() => {
                run();
              }).bind(this);
            }).bind(this);
          }).bind(this);
        }).bind(this);
      }).bind(this);
    }).bind(this);
  }).bind(this);
}).bind(this);
  • 콜백지옥이라 불리는 연속적 콜백
  • 이 경우 유지보수가 불가능할 정도의 복잡함을 가지게 됨
  • this의 문맥 유지를 위해 bind 해줬지만 실제 상황에서는 this가 어디 문맥의 this 인지 혼동할 가능성이 높음
profile
컴퓨터가 좋아

0개의 댓글