JS/드림코딩앨리

11. 비동기 처리의 시작 콜백 이해하기, 콜백 지옥 체험

배워도끝이없네 2021. 4. 21. 12:39
'use strict'

//var선언이나 function같은것들을 선언하면 자동적으로 가장위에서 선언된것처럼 되는것을 호이스팅이라고 한다.

console.log('1');
setTimeout(()=>{console.log("2")},1000); //callback함수를 n초 후에 실행시켜줘 
console.log('3');

//Synchronous callback
function printImmediately(print){
    print();
}

printImmediately(()=>{console.log('hello')});

//Asynchronous callback

function printWithDelay(print,timeout){
    setTimeout(print,timeout);
}

printWithDelay(()=>console.log('async callback'),2000);


//콜백 지옥 예제 만들어보기

class UserStorage{
    loginUser(id, password, onSuccess, onError){
        setTimeout(()=>{
            if(
                (id==='ellie' && password === 'dream') ||
                (id ==='coder' && password === 'academy')
            )
            {
                onSuccess(id);
            }else{
                onError(new Error('not found'));
            }
        },2000);
    }

    getRoles(user,onSuccess, onError){
        setTimeout(()=>{
            if(user === 'ellie'){
            onSuccess({name:'ellie',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)}
);

 

콜백지옥..이해가너무힘들다..