콜백지옥

장서연·2021년 6월 30일
0
'use strict'
// Javascript is synchronous!
// Execute the code block by order after hoisting
// hoisting : var, function declaration

// 자바스크립트 엔진은 모든 변수와 함수의 선언블록을 가장 위로 올린다음, 
// 순차적으로 코드를 해석한다.

console.log(1)

// browser's api
setTimeout(()=>console.log(2),1000) // 브라우저에게 요청
console.log(3)

// Synchronous callback
function printImmediately(print){
    print()
}
printImmediately(()=>console.log('hello!'))

// Asynchronous callback
function printWithDelay(print, timeout){
    setTimeout(print, timeout)
}
printWithDelay(()=>console.log('this is async callback'), 2000) // 브라우저에게 요청

// Callback Hell example
// 백엔드(서버)에서 사용자의 데이터를 받아오는 클래스
// 두가지의 api가 있다고 가정
class UserStorage{
    loginUser(id, password, onSuccess, onError){
        setTimeout(()=>{
            if ((id === 'ellie' && password === 'dream') ||
               (id === 'coder' && password === 'academy') 
            ){
                onSuccess(id);
            }else{
                onError(new Error('not found...'))
            }
        }, 2000)
    }
    getRoles(user, onSuccess, onError){
        setTimeout(()=>{
            if (user === 'ellie'){
                onSuccess({name:'ellie', role:'admin'});
            }else{
                onError(new Error('no access...'))
            }
        },1000)
    }
}

const userStorage = new UserStorage();
const id = prompt('please enter your id')
const password = prompt('please enter your password')

userStorage.loginUser(id, password, (user) =>{
    userStorage.getRoles(user, userWithRole=>{
        alert(`Hello ${userWithRole.name}, you hava a ${userWithRole.role}`)
    }, error =>{})
}, (error)=>{console.log(error)})

0개의 댓글