ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [JavaScript] Callback
    JavaScript 2022. 2. 19. 01:20
    728x90
    반응형

    Callback  동기 vs 비동기

    "use strict";
    
    // JavaScript is synchronous.
    // Execute the code block by orger after hoisting.
    // hoisting: var, function declaration
    console.log('1');
    setTimeout(() => console.log('2'), 1000);
    console.log('3');
    
    // Synchronous callback // 동기 callback
    function printImmediately(print){
        print();
    }
    printImmediately( () => console.log('hello'))
    
    
    // Asynchronous callback // 비동기 callback
    function printWithDelay(print, timeout){
        setTimeout(print, timeout);
    }
    printWithDelay(()=> console.log('async callback'), 2000);

     

    콜백 지옥..

    // Callback hell example
    class UserStorage {
        loginUser(id, password, onSuccess, onError) {
            setTimeout(() => {
                if (
                    (id === 'wonju' && password === 'turtle') ||
                    (id === 'coder' && password === 'academy')
                ) {
                    onSuccess(id);
                } else {
                    onError(new Error('not found'));
                }
            }, 2000);
        }
    
        getRoles(user, onSuccess, onError) {
            setTimeout(() => {
                if (user === 'wonju') {
                    onSuccess({name: 'wonju', 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`)
                },
                erroe => {
                    console.log(erroe);
                }
            );
        },
        error => {
            console.log(error);
        }
    );

     

     

    promise를 이용한 콜백지옥 정리

    class UserStorage {
        loginUser(id, password) {
            return new Promise((resolve, reject) => {
                setTimeout(() => {
                    if (
                        (id === 'wonju' && password === 'turtle') ||
                        (id === 'coder' && password === 'academy')
                    ) {
                        resolve(id);
                    } else {
                        reject(new Error('not found'));
                    }
                }, 2000);
            })
        }
    
        getRoles(user) {
            return new Promise((resolve, reject) => {
                setTimeout(() => {
                    if (user === 'wonju') {
                        resolve({name: 'wonju', role: 'admin'});
                    } else {
                        reject(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)
        .then(userStorage.getRoles)
        .then(user => alert(`Hello ${user.name}, you have a ${user.role} role`))
        .catch(console.log);
    LIST

    'JavaScript' 카테고리의 다른 글

    [JavaScript] addEventListener  (0) 2022.05.24
    [JavaScript] Promise, Async & Await  (0) 2022.02.22
    [JavaScript] JSON  (0) 2022.02.19
    [JavaScript] 유용한 배열(Array) API 10가지  (0) 2022.02.17
    [JavaScript] 배열(Array)  (0) 2022.02.17
Designed by Tistory.