자바스크립트 콜백함수 | JavaScript Callback

YuJin Lee·2021년 8월 10일
0

Javascript

목록 보기
19/22

출처: https://www.youtube.com/watch?v=s1vpVCrT8f4&t=1093s (엘리의 드림코딩)

Javascript is synchronous
Execute the code block in order after hoisting

자바스크립트는 동기적이다.
호이스팅이 일어난 후부터 차례대로 코드가 실행된다.

  • 콜백함수는 원할 때 다시 불러오는 함수이다.
console.log("1");
setTimeout(() => console.log("2"), 1000);
// setTimeout(콜백함수, 지연시간)
// 인자로 만든 함수를 전달해준다.
// 원할 때 다시 불러오는 함수 --> 콜백 함수
console.log("3");
// 3이 출력된 후 2가 출력된다.

콜백함수는 Synchronous callback과 Asynchronous callback로 나뉘어진다.

  • Synchronous callback
    즉각적으로, 동기적으로 실행하는 콜백함수
function printImmediately(print) {
  print();
  // 콜백함수 print를 실행하는 함수
}
// 호이스팅 되어 함수 선인이 제일 위로 올라간다.

printImmediately(() => console.log("hello"));
// 함수를 실행하면 바로 'hello'가 출력된다.

  • Asynchronous callback
    언제 실행될 지 알 수 없는 비동기 콜백함수
function printWithDelay(print, timeout) {
  setTimeout(print, timeout);
}

printWithDelay(() => console.log("async callback"), 2000);

  • Callback Hell example
class UserStorage {
  // 사용자의 id와 password를 받아와서 성공인지 에러인지 확인하는 API
  loginUser(id, password, onSuccess, onError) {
    setTimeout(() => {
      if (
        (id === "ellie" && password === "dream") ||
        (id === "coder" && password === "academy")
      ) {
        onSuccess(id);
      } else {
        onError(new Error("not found"));
      }
    }, 2000);
  }

// 사용자의 Role을 받아오는 API
  getRoles(user, onSuccess, onError) {
    setTimeout(() => {
      if (user === "ellie") {
        onSuccess({ name: "ellie", role: "admin" });
      } else {
        onError(new Error("no access"));
      }
    }, 1000);
  }
}

// 새로운 클래스 선언
const userStorage = new UserStorage();

// 사용자에게 id와 password 받아오기
const id = prompt("enter your id");
const password = prompt("enter your password");

// 1. 사용자에게 id, password 받아오기
// 2. 받아온 데이터를 서버에게 넘겨서 login
// 3. 받아온 id를 이용해서 역할 받아오기
// 4. 역할이 성공적으로 받아와 진다면 이름과 역할 출력하기
userStorage.loginUser(
  id,
  password,
  //성공했을 때 사용자 id 받아오기
  (user) => {
    // 사용자의 역할 받아오기
    userStorage.getRoles(
      user,
      // 역할 받아오기 성공했을 때
      (userWithRole) => {
        alert(`Hello ${userWithRole.name}, you have a ${userWithRole.role} role!`);
      },
      // 역할 받아오기 실패했을 때
      (error) => {
        console.log(error);
      }
    );
  },
  // 실패했을 때 error 받아오기
  (error) => {
    console.log(error);
  }
);
  • 콜백 체인의 문제점

콜백 함수 안에서 또 다른 것을 호출하고 그 안에서 또 다른 콜백을 전달하고 또 호출하고...
이것을 반복하는 것이 콜백 지옥이다.

이런 콜백 체인은 다음과 같은 문제점이 있다.
가독성이 매우 떨어진다.
로직을 이해하기 어렵다.
어디에서 에러가 발생하는지 찾기 어렵다.
디버깅 하기에 힘들다.
유지보수가 어렵다.

profile
배운 것을 기록하는 곳 💻🙂

0개의 댓글