async & await → clear style of using promise
무조건 async 와 Promise 를 같이 사용해야 맞는 게 아니라 Promise 만 사용해야 하는 경우도 있다.
async 로 코딩하기 → https://www.youtube.com/watch?v=_9vgd9XKlDQ
callback hell 예시 (async 로 보완)
// CallBack Hell example
class UserStorage {
async loginUser(id, password) {
if(
(id === 'ellie' && password === 'dream') ||
(id === 'coder' && password === 'academy')
) {
await delay(1000);
return id;
}
else {
return new Error('not found');
}
}
async getRoles(user) {
if(user === 'ellie') {
await delay(1000);
return { name: 'ellie', role: 'admin' };
}
else {
return new Error('no access');
}
}
delay(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
}
// 실행
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) => alert(`Hello ${user.name}, you have a ${user.role} role`))
.catch(console.log);