Notice
Recent Posts
Recent Comments
«   2025/06   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
Today
Total
관리 메뉴

IT CUBE

[JavaScript] 자바스크립트 기본 Part 4 본문

Front-End

[JavaScript] 자바스크립트 기본 Part 4

CUBE 2021. 10. 7. 21:25

 

 

자바스크립트는 hoisting 된 후에 코드가 순서대로 실행됩니다. (Synchronous)

* hoisting이란? (최근 면접에서 들어오는 질문 중 하나)

var나 function 선언들이 자동적으로 맨 위로 올라가는 것

 

Synchronous와 Asynchronous

//동기적인 예 (Synchronous)
console.log('1');
console.log('2');
console.log('3');
// 1 2 3 출력

// 비동기적인 예 (Asynchronous)
console.log('1');
setTimeout(()=>console.log('2'),1000);
console.log('3');
//1 3 2 출력

 

Synchronous Callback과 Asynchronous Callback

//Syncronous Callback
function printImmadiately(print){
    print()
}
printImmadiately(()=>console.log('hello'));


//Asyncronous Callback
function printWithDelay(print,timeout){
    setTimeout(print,timeout);
}
printWithDelay(()=>console.log('async callback'),2000);

 

콜백을 너무 많이 사용한 콜백 체인(콜백 지옥)

class UserStorage{
    loginUser(id, password, onSuccess, onError){
        setTimeout(()=>{
           //백엔드가 없기 때문에 timeout으로 예제
            if(
                (id === 's1' && password === '1')||
                (id === 's2' && password === '2')
            ){
                onSuccess(id);
            }else{
                onError(new Error('not found'));
            }

        },2000);
    }
    
    getRoles(user, onSuccess, onError){
        setTimeout(()=>{
            if(user==='s1'){
                onSuccess({name: 's1', role: 'admin'});
            }else{
                onError(new Error('no access'));
            }
        })
    }
}

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

사용자의 id와 password를 입력받아 해당 사용자의 역할을 불러오는 예제입니다.

콜백을 여러번 사용하여 코딩을 할 수는 있지만 단점이 존재합니다.

한눈에 봐도 가독성이 떨어지고 비즈니스 로직을 확인하기 어렵고, 특히 오류 발생 시 어디서 오류가 발생했는지 쉽게 알 수 없습니다.