[ javascript ] 콜백지옥 - callback > javascript&jQuery

본문 바로가기

사이트 내 전체검색

javascript&jQuery

[ javascript ] 콜백지옥 - callback

작성일 21-02-21 01:42

페이지 정보

작성자 웹지기 조회 3,301회 댓글 0건

본문

'use strict'


//JavaScript is synchronous.

//Execute the code block by orger after hoisting.

//hoisting: var, function declearation

//1. 동기와 비동기

console.log('1'); //동기식

setTimeout(function(){ //비동기식

    console.log('2');//브라우져에서 함수에 의해 대기했다가 실행(비동기 실행방법)

},1000);

// 여기서 function 으로 사용되는 callback 함수는

// arrow function expression으로 변경이 가능

//변경하게 되면

setTimeout( () => console.log('4'), 1000); //비동기식

//이러한 형태로 변경이 가능하다.

console.log('3'); //동기식


//Synchronous callback (동기적)

function printImmediately(print) {

    print();

}

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


//Aynchronous 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 === 'test'  && password === 'dream') ||

                (id === 'coder' && password === 'academy')

            ) {

                onSuccess(id);

            } else {

                onError(new Error('not found'));

            }

        }, 2000);

    }


    getRoles(user, onSuccess, onError) {

        setTimeout(() => {

            if(user === 'test') {

                onSuccess({name:'test', role:'admin'});

            } else {

                onError(new Error('no access'));

            }

        }, 1000);

    }

}


//1. 사용자에게 아이디 비밀번호 받아와서 로그인

//로그인이 성공이면 역할을 요청해서 받아온다.

//역할이 성공적으로 받아지면 object를 출력한다.

const userStorage = new UserStorage();

const id = prompt('enter you id');

const password = prompt('enter your password');

userStorage.loginUser(

    id, 

    password, 

    (user) => {

        userStorage.getRoles(

            user, 

            userWithRole => {

                alert(`Hello ${userWithRole.name}, you hava a ${userWithRole.role} role`);

            },

            error => {

                console.log(error);

            }

        );

    },

    error => {console.log(error)}

);


추천0

비추천 0

댓글목록

등록된 댓글이 없습니다.

전체 63건 1 페이지

이미지 목록

게시물 검색
Copyright © 즐거운 코딩 생활 ( funyphp ). All rights reserved.
PC 버전으로 보기