ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Javascript] callback 함수와 callback 지옥
    IT&컴퓨터공학/Javascript 2021. 1. 21. 13:10

     

    Javascript 는 기본적으로 synchronous ( 동기적 ) 이다

    즉 , *호이스팅 되고나서 순서에 따라 하나하나씩 실행된다

    *호이스팅 : var 변수 / function declaration 들이 자동으로 제일 위로 올라가는 것

     

     

    callback function 

    자바스크립트의 asynchronous ( 비동기성 ) 을 표현하는 가장 일반적인 기법

    → 파라미터로 함수를 전달하는 함수 

     

    • Synchronous callback
    console.log('1');
    setTimeout( () => console.log('2'), 1000 ); // 1초뒤에 2를 출력해라
    console.log('3');
    
    function printImmediately(print){
    	print();
    }
    
    printImmediately( ()=> console.log('hello') );
    
    // 결과 : 1,3,hello,2  순서

     

    위의 코드는 실제로 자바스크립트에서 어떻게 동작할까 ?

    function printImmediately(print){  // 호이스팅 때문에 함수 선언부가 위로 올라옴
    	print();
    }
    
    console.log('1');
    setTimeout( () => console.log('2'), 1000 ); 
    console.log('3');
    
    printImmediately( ()=> console.log('hello') );
    
    

     

    • Asynchronous callback
    console.log('1');
    setTimeout( () => console.log('2'), 1000 ); // 1초뒤에 2를 출력해라
    console.log('3');
    
    function printDelay(print,time){
    	setTimeout(print,time);
    }
    
    printDelay( ()=> console.log('hello'),2000 );
    
    // 결과 : 1,3,2,hello  순서

    비동기라서 printDelay 는 print 함수를 바로 부르지않고, 2초를 기다리고 다시 callback 한다. 

     

     

    • 콜백지옥 코드
    // 콜백 지옥 example 
    
    // 사용자에게 id / password 를 받고 유효한 계정이면 role 까지 출력
    
    
    class UserStorage{
    
        loginUser(id,password,onSuccess,onError){
            setTimeout( () => {
                if(
                    (id==='coding' && password==='funny') ||
                    (id==='studying' && password==='interesting')
                ){
                    onSuccess(id);
                }
                else{
                    onError(new Error('not found'));
                } 
            },2000); // 로그인하는데 2초
        }
    
        getRole(user,onSuccess,onError){
            setTimeout( () => {
                if(user==='coding'){
                    onSuccess({name : 'coding', role:'admin'});
                }
                else{
                    onError(new Error('no access'));
                }
            },1000) // 역할을 반환하는데 1초
        }
    }
    
    
    // 코드구현
    
    const userStorage = new UserStorage();
    
    const id = prompt('enter your id ');
    const password = prompt('enter your password ');
    
    userStorage.loginUser(
        id,
        password,
        (user)=>{
            userStorage.getRole(
                user,
                (userWithRole)=>{
                    alert('hello'+userWithRole.name+" your role is "+userWithRole.role);
                },
                error =>{
                    console.log(error);
                }
            )
        },
        error =>{
            console.log(error);
        }
    )

    단점

    1. 가독성이 너무 떨어짐. error 가 뜰때 어디에서 error 가 떳는지 찾아내기 힘듬

    2. 유지보수도 어려움

     

     

     

    그렇다면 이 비동기 코드를 어떻게 하면 깔끔하게 작성할 수 있을까 ?  다음편에 계속 !

    댓글

Designed by Tistory.