Callback Hell ์์
์ด์ ์๊ฐ์ ๋ง๋ค์๋ ์ฝ๋ฐฑ์ง์ฅ ์์๋ค.
// ๊ธฐ๋ณธ์ธํ
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, onSuccess, onError) {
setTimeout(() => {
if (user === 'master') {
onSuccess({name: 'Master', role : 'admin'});
} else {
onError(new Error('Go away!'));
}
}, 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(
'Hello ${userWithRole.name}, you have a ${userWithRole.role} role'
);
},
error => {
console.log(error);
}
);
},
error => {
console.log(error);
}
);
์ด๋ฅผ promise๋ฅผ ์ด์ฉํด ๊น๋ํ๊ฒ ๊ฐ์ ํด ๋ณด์.
๊ฐ์ ๋ ์ฝ๋
class UserStorage {
loginUser(id, password) { //onSuccess, onError๊ฐ์ ์ฝ๋ฐฑํจ์๋ฅผ ๋ง๋ค ํ์๊ฐ ์๋ค.
return new Promise((resolve, reject) => { //์๋ก์ด promise๋ฅผ ๋ง๋ ๋ค.
setTimeout(() => {
if (
(id === 'master' && password === 'master00') ||
(id === 'submaster' && password === 'submaster00')
) {
resolve(id); //onSuccess ๋์ resolve
} else {
reject(new Error('not found')); //onError ๋์ reject
}
}, 2000);
});
}
getRoles(user) {//onSuccess, onError๊ฐ์ ์ฝ๋ฐฑํจ์๋ฅผ ๋ง๋ค ํ์๊ฐ ์๋ค.
return new Promise((resolve, reject) => { //์๋ก์ด promise๋ฅผ ๋ง๋ ๋ค.
setTimeout(() => {
if (user === 'master') {
resolve({name: 'Master', role : 'admin'}); //onSuccess ๋์ resolve
} else {
reject(new Error('Go away!')); //onError ๋์ reject
}
}, 1000);
});
}
}
const userStorage = new UserStorage();
const id = prompt('Enter your id');
const password = prompt('Enter your password');
userStorage
.loginUser(id, password)
.then(userStorage.getRoles) //.then(user => userStorage.getRoles)์์ ์ถ์ฝ ๊ฐ๋ฅ (์ธ์๊ฐ ๊ฐ์ผ๋ฏ๋ก)
.then(user => alert(`Hello ${user.name}, you have a ${user.role} role`))
.catch(console.log);
์ถ์ฒ : ๋๋ฆผ์ฝ๋ฉ https://www.youtube.com/@dream-coding / MDN https://developer.mozilla.org/ko/