예시를 위한 간단 클래스
class UserStorage {
loginUser(id, password, onSuccess, onError) {
setTimeout(() => {
if (
(id === 'nightohl' && password === 'myworld') ||
(id === 'guest' && password === 'test')
) {
onSuccess(id);
} else {
onError(new Error('not found'));
}
}, 2000);
}
getRoles(user, onSuccess, onError) {
setTimeout(() => {
if (user === 'nightohl') {
onSuccess({ name: 'nightohl', 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 => {
userStorage.getRoles(
user,
userWithRole => {
alert(`Hi ${userWithRole.name}, you have a ${userWithRole.role} role`);
},
error => {
console.log(error);
},
);
},
error => {
console.log(error);
},
);
단점