jsNote 12: Callback to promise


jsNote 10および11で説明したcallbackおよびpromiseを使用して、既存のコードをクリーンにします.
class UserStorage{
    loginUser(id, password){
        return new Promise((resolve, reject) => {
            setTimeout(()=>{
            if(
                (id === 'emma' && password === 'Emma') ||
                (id === 'coder' && password === 'Coder')
            ) {
                resolve(id); 
            } else{
                reject(new Error('not found')); 
            }
        }, 2000);
        });
    }

    getRoles(user) {
        return new Promise ((resolve, reject) => {
             setTimeout(() => {
            if(user === 'emma'){
                resolve({name: 'emma', role: 'admin'});
            } else{
                reject(new Error('no access'));
            }
        }, 1000);
        });
    }
}

//1)입력 받아온 id와 password를 이용해 
//2)login
//3)받아온 id를 이용해 role을 받아옴

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);