November 11, 2020
https://dev-seolleung2.netlify.app/development/CallbackHell/
์ ๋งํฌ ๋ธ๋ก๊ทธ ๋ง๋ฏธ์ ์์๋ฅผ ๊ทธ๋๋ก ๊ฐ์ ธ์๋ค.
// ๋ฐฑ์๋์์ id, password ๋ฅผ ๊ฐ์ ธ์ค๋ ์ ์ฅ์ UserStorage.
// ํ์ง๋ง ์ฝ๋ฐฑ ์ง์ฅ์ด๋ค.
class UserStorage {
loginUser(id, password, onSuccess, onError) {
setTimeout(() => {
if (
(id === 'seolleung2' && password === 'iamhandsome') ||
(id === 'gdragon' && password === 'yakkuk')
) {
onSuccess(id)
} else {
onError(new Error('not Found'))
}
}, 2000)
}
getRoles(user, onSuccess, onError) {
setTimeout(() => {
if (user === 'seolleung2') {
onSuccess({ name: 'seolleung2', 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(
`Hello ${userWithRole.name}, you have a ${userWithRole.role} role`
)
},
error => {
console.log(error)
}
)
},
error => {
console.log(error)
}
)
Callback Hell ์ฝ๋๋ฅผ Promise ๋ก ๋ฐ๊พธ๋ ์ฐ์ต์ ํด๋ดค๋ค!
class UserStorage {
loginUser(id, password) {
// ๋ ์ด์ onSuccess, onError ๊ฐ์ ์ฝ๋ฐฑ ์ ๋ฌ๋ฐ์ ํ์๊ฐ ์๋ค.
return new Promise((resolve, reject) => {
setTimeout(() => {
if (
(id === 'seolleung2' && password === 'iamhandsome') ||
(id === 'gdragon' && password === 'yakkuk')
) {
resolve(id)
} else {
reject(new Error('not Found'))
}
}, 2000)
})
}
getRoles(user) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (user === 'seolleung2') {
resolve({ name: 'seolleung2', role: 'admin' })
} else {
reject(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)
.then(userStorage.getRoles) // .then(user => userStorage.getRoles(user)) ์ ๋์ผ
.then(user => alert(`Hello ${user.name}, you have a ${user.role} role`))
.catch(console.log)
์ค ์ข๋ค์ข์!
์์ ์ฝ๋๋ ์๋ฌด ๋ฌธ์ ์์ด ๋์๊ฐ๋ค!