본문 바로가기
프론트엔드/바닐라 자바스크립트

비동기 처리의 시작 콜백 이해하기

by juneMiller 2021. 12. 7.

callback.js 

'use strict'

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

}

//Asynchronous callback
function printWithDelay(print, timeout) {
    setTimeout(print, timeout);
}

//JavaScript is synchronouse. 
//Execute the code block by orger after hoisting.
//hoisting: var, funcition declaration 

console.log('1');
setTimeout(() => console.log('2'), 1000);
//console.log('2');
console.log('3');

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

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


//Callback Hell example 
class UserStorage {
    loginUser(id, password, onSuccess, onError) {
        setTimeout(()=> {
            if(
                (id === 'june' && password === 'young') ||
                (id === 'coder' && password === 'academy')
            ){
                onSuccess(id);
            }else{
                onError(new Error('not found'));
            }
        }, 2000);
    }

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