[JS] Javascript #10 Summary

1 minute read

Javascript #10 Summary


Callback

  • Callback Function: 전달해준 함수를 나중에 call 해달라는 의미의 함수

  • Javascript is synchronous. (Execute the code block by order after hoisting.)

  • hoisting: var, function declaration.

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

>>> 1
>>> 3
>>> 2



Synchronous Callback

  • 즉각적, 동기적으로 실행
console.log('1');
setTimeout(() => console.log('2'), 1000);
console.log('3');

function printImmediately(print) {  // hoisted
    print():
}
printImmediately(() => console.log('hello'));  // hello

>>> 1
>>> 3
>>> hello
>>> 2



Asynchronous Callback

  • 나중에, 언제 실행될지 예측할 수 없음
console.log('1');
setTimeout(() => console.log('2'), 1000);
console.log('3');

function printImmediately(print) {  // hoisted
    print();
}

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

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

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

>>> 1
>>> 3
>>> hello
>>> 2
>>> async callback


위의 코드를 정리하면 다음과 같다.

function printImmediately(print) {  // hoisted
    print();
}
function printWithDelay(print, timeout) {  // hoisted
    setTimeout(print, timeout);
}

console.log('1');  // 동기
setTimeout(() => console.log('2'), 1000);  // 비동기
console.log('3');  // 동기
printImmediately(() => console.log('hello'));  // 동기
printWithDelay(() => console.log('async callbaack'), 2000);  // 비동기

>>> 1
>>> 3
>>> hello
>>> 2
>>> async callback



Callback Hell Example

  • Callback Chain
class UserStorage {
    loginUser(id, password, onSuccess, onError) {
        setTimeout(() => {
            if (
                (id === 'bruce' && password === 'dev') ||
                (id === 'bruce2' && password === 'dev2')
            ) {
                onSuccess(id);
            } else {
                onError(new Error('not found'));
            }
        }, 2000);
    }
    getRoles(user, onSuccess, onError) {
        setTimeout(() => {
            if (user === 'bruce') {
                onSuccess({name: 'bruce', 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);
    }
);

Leave a comment