동캄의 코딩도장

JS [callback-to-promise 예제] 본문

front/HTML&CSS&JS

JS [callback-to-promise 예제]

동 캄 2022. 1. 25. 11:56
// Callback kHell example
class userStorage{
    loginUser(id,password){
        return new Promise((resolve,reject)=>{
            setTimeout(()=>{
                if(
                    (id==='ellie' && password ==='dream') ||
                    (id ==='coder' && password ==='academy')
                ){
                    resolve(id);
                }
                else{
                    reject(new Error('not found'));
                }
            },2000);
        });
    }
    getRoles(user){
        return new Promise((resolve,reject)=>{
            setTimeout(()=>{
                if(user==='ellie'){
                    resolve({name:'ellie',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=>alert(`Hello ${user.name}, you have a ${user.role} role`))
.catch(console.log);

'front > HTML&CSS&JS' 카테고리의 다른 글

JS [콘솔 사용 tip]  (0) 2022.01.27
JS [async]  (0) 2022.01.25
JS [promise]  (0) 2022.01.25
JS [call back]  (0) 2022.01.25
JS [JSON]  (0) 2022.01.25