비동기 처리의 시작 콜백 이해하기, 콜백 지옥 체험😱
//JavaScript is synchronous.
//Execute the code block in order after hoisting.
//hoisting: var, function declaration
console.log('1');
setTimeout(function() {
console.log('2');
}, 1000);
console.log('3'); // 132순서대로 보인다. setTimeout()은 asynchronous한 실행방법, 콜백함수: call(불러줘)back(나중에)
//synchronous callback 콜백의 동기적 실행
function printImmediately(print) {
print();
}
printImmediately(() => console.log('hello'))
//출력
//1, 3, hello, 2
//hoisting에 의해 함수 선언 제일 위로 이동, 차례대로 내려오면서 실행, setTimeout()에 의해 마지막으로 2 출력
//asynchronous callback 콜백의 비동기적 실행
function printWithDelay(print, timeout) {
setTimeout(print, timeout);
}
printWithDelay(() => console.log('async callback'), 2000);
//출력
//1, 3, hello, 2, async callback
//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);
}
const userStorage = new UserStorage();
const id = prompt('enter your id');
const password = prompt('enter your password');
userStorage.loginUser(id, password, (user) => {
id,
password,
user => {
userStorage.getRoles(user, (userWithRole) => {
alert(`Hello ${userWithRole.name}, you have a ${userWirhRole} role`)
},
error => {
console.log(error)
});
},
error => {console.log(error)},
});
}
// 실행은 되지만 콜백지옥이 완성되었다...
//가독성 떨어짐, 로직 이해 떨어짐, 유지보수 어려움 등의 단점이 있다.