개발 공부/자바스크립트

[엘리의 드림코딩 JS] 11. callback

5묘 2022. 12. 6. 09:26

https://youtu.be/s1vpVCrT8f4

'use strict';

// JavaScript is synchronous.
// Execute the code block by order after hoisting.
// hoisting : var, function declaration
console.log('1');
setTimeout(() => console.log('2'), 1000);
console.log('3');

// Synchronous callback
function printImmediately(print) {
  print();
}
printImmediately(() => console.log('hello'));

// Asynchronous callback
function printWithDelay(print, timeout) {
  setTimeout(print, timeout);
}
printWithDelay(() => console.log('async callback'), 2000)


// Callback Hell example
class UserStorage {
  loginUser(id, password, onSuccess, onError) {
    setTimeout(() => {
      if (
        (id === 'ellie' && password === 'dream') ||
        (id === 'coder' && password === 'academy')
      ) {
        onSuccess(id);
      } else {
        onError(new Error('not found'));
      }
    }, 2000);
  };

  getRoles(user, onSuccess, onError) {
    setTimeout(() => {
      if (user === 'ellie') {
        onSuccess({ name: 'ellie', role: 'admin' });
      } else {
        onError(new Error('no access'));
      }
    }, 1000);
  }
}

//콜백 체인(콜백 지옥)의 문제점
// 1. 가독성이 너무 어려움
// 2. 디버깅, 에러 발생 시 발생 위치 찾기 힘듦
const userStorage = new UserStorage();
const id = prompt('enter your id') // 브라우저 API
const password = prompt('enter your password')
userStorage.loginUser(
  id,
  password,
  user => {
    userStorage.getRoles(
      user, 
      userWithRole => {
        alert(`hello ${userWithRole.name}, you have a ${userWithRole.role} role.`);
      },
      error => {
        console.log(error);
      }
    );
  },
  error => {
    console.log(error)
  }
);