🟨 JavaScript/개념
[드림코딩] 콜백함수 (1) : 콜백지옥 예시
Zoeeey
2022. 7. 22. 14:11
콜백지옥
// 기본세팅
class UserStorage {
loginUser(id, password, onSuccess, onError) {
setTimeout(() => {
if (
(id === 'master' && password === 'master00') ||
(id === 'submaster' && password === 'submaster00')
) {
onSuccess(id);
} else {
onError(new Error('not found'));
}
}, 2000);
}
getRoles(user, onSucces, onError) {
setTimeout(() => {
if (user === 'master') {
onSuccess({name: 'Master', role : 'admin'});
} else {
onError(new Error('Go away!'));
}
}, 1000);
}
}
좋지 않은 콜백지옥 예시
(id와 password를 검사해서 id가 master일 경우 admin role을 부여하는 코드이다.)
//콜백지옥
const userStorage = new UserStorage();
const id = prompt('Enter your id');
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);
}
);
문제점
- 가독성이 떨어진다. (logic을 알아보기 힘들다)
- 에러가 발생했을 시 디버깅하기 어렵다.
출처 : 드림코딩 https://www.youtube.com/@dream-coding / MDN https://developer.mozilla.org/ko/