10. JS Basic (Callback)

Changmok LEE·2023년 2월 15일

Callback

JavaScript is synchronous
excute the code block by order after hoisting.
hoisting: var, function declaration

console.log('1');
setTimeout(function () {
    console.log('2');
}, 1000);
console.log('3');

// 출력: 1, 3, 2

1. Synchronous Callback

동기

// Synchrconous Callback
function printImmediately(print) {  // hoisting
    print();
}

console.log('1');
setTimeout(function () {
    console.log('2');
}, 1000);
console.log('3');

printImmediately(() => console.log('hello'));

// 1,3,hello,2

2. Asynchronous Callback

비동기

// Synchrconous Callback
function printImmediately(print) { // hoisting
    print();
}

// Asynchrconous Callback
function printWithDelay(print, timeout) { // hoisting
    setTimeout(print, timeout);
}

console.log('1');
setTimeout(function () {
    console.log('2');
}, 1000);
console.log('3');

printImmediately(() => console.log('hello'));
printWithDelay(() => console.log('async callback'), 2000);

// 1,3,hello,2,async callback

3. Callback Hell (콜백지옥)

문제점

  • 가독성 떨어짐(안에서 호출하고 호춯하고 ~ 반복)
  • promise와 async 사용해서 해결 가능
// Callback Hell Example

// 임시 back-end 구성
class UserStorage {
    // back-end 통신시간 존재한다고 가정
    loginUser(id, password, onSuccess, onError) {
        setTimeout(() => {
            if (
                (id === 'eelkom' && password === 'lee') ||
                (id === 'coder' && password === 'lee')
            ) {
                onSuccess(id);
            } else {
                onError(new Error('not found'));
            }
        }, 2000);
    }
    getRoles(user, onSuccess, onError) {
        setTimeout(() => {
            if (user === 'eelkom') {
                onSuccess({ name: 'eelkom', role: 'admin' });
            } else {
                onError(new Error('no sccess'));
            }
        }, 1000);
    }
}

// back-end 불러오기
const userStorage = new UserStorage(); // class 생성
const id = prompt('enter your id');
const password = prompt('enter your password');
userStorage.loginUser(
    id,
    password,
    (user) => {
        userStorage.getRoles(
            user,
            (userWithRoles) => {
                alert(`Hello ${userWithRoles.name}, you have a ${userWithRoles.role} role`);
            },
            (error) => {console.log(error)}
        );
    },
    (erorr) => {console.log(error)}
);
profile
이창목

0개의 댓글