📔
web_study
  • JavaScript
  • 엘리_자바스크립트
    • 자바스크립트 기본
      • 클래스 예제와 콜백함수
      • 연산자 boolean
      • 함수 정의, 호출 그리고 콜백
      • 변수타입과 object 차이점
    • JavaScript async 와 await
    • JavaScript Promise
    • 자바스크립트 callback
    • 자바스크립트 json
    • 유용한 10가지 배열 함수들
    • 자바스크립트 배열(array)
    • 자바스크립트 object
    • 자바스크립트 (class vs object) 객체지향 언어
    • 자바스크립트 함수
    • 자바스크립트 연산.반복문
    • 데이터타입, data types, let vs var, hoisting
    • script async 와 defer의 차이점 콘솔 출력
    • 자바스크립트역사
  • 생활코딩
    • 재귀함수
    • 정규 표현식
    • 객체지향
      • 객체지향 프로그래밍
      • 생성자와 new
      • 전역객체
      • this
      • 상속
      • prototype
      • 표준 내장 객체의 확장
      • object
      • 데이터 타입
      • 참조
    • 함수지향
      • 유효범위
      • 값으로서의 함수와 콜백
      • 클로저
      • arguments
      • 함수의 호출
    • UI API, 문서
    • 모듈
    • 객체
    • 배열
    • 함수
    • 반복문
    • 조건문
    • 숫자와문자
    • 변수
    • 비교
  • 노마드 코더
    • Getting the Weather part One Geolocation
    • Image Background
    • TO DO List
    • Saving the User Name
    • Clock part One
    • 조건문 ( if , else, and, or)
    • evnet handlers
    • Function
    • Objects
    • Arrays
    • Variable(변수!)
    • Javascript
  • javascript30
    • Dram Kit
    • clock
    • Css Javascript
    • Array Cardio
    • flex panels
    • type ahead
    • Canvas Draw
    • Speech Synthesis
    • Whack A Mole
  • web standard
    • script 부분
    • form부분
    • 웹접근성
    • <meta>
  • 자바스크립트_이론
    • 기본지식(JAVASCRIPT)
    • 기본지식(CSS)
    • 기본지식(HTML)
    • 기본지식(HTTP)
    • Dom
    • 라이브러리, 프레임워크, 플로그인
Powered by GitBook
On this page
  • 동기와 비동기
  • 콜백지옥체험

Was this helpful?

  1. 엘리_자바스크립트

자바스크립트 callback

동기와 비동기

'use script'
// JavaScript is synchronous.
// 자바스크립트는 동기적인 프로그래밍 언어이다.
// hoisting: var, function dectaration 
// hoisting: 함수 안에 있는 선언들을 모두 끌어올려서 해당 함수 유효 범위의 최상단에 선언하는 것

console.log('1');
setTimeout(()=>console.log('2'),1000); // 브라우저 요청 -> 1초 후 실행 
console.log('3');   
// 1 3 2 출력
// => 비동기적인 실행 방법

//Synchronous callback (동기) 
// 함수의 선언은 호이스팅 되기때문에 제일 위로 가게됨 
function printImmediately(print){
    print();
}
 printImmediately(()=> console.log('hello'));
 
 
// Asynchronous callback (비동기)
// 함수의 선언은 호이스팅 되기때문에 제일 위로 가게됨 
function printWithDelay(print, timeout){
  setTimeout(print, timeout);
}
printWithDelay(()=> cosole.log('Async CallBack'),2000); // 제일 마지막에 출력

// callback hell example
// 콜백지옥의 예시
  // 아이디가 엘리이고 패스워드가 드림 이거나 아이디가 코더 비밀번호가 아케데미라면 onSucces의 아이디를 불러줌
  // 만약 아니라면 not found를 화면에 출력해라 2초뒤 실행
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')); // 에러 'not found'
            }
        }, 2000);
    }
    // 사용자가 엘리이면 이름은 엘리고 role 은 어드민인 값을 전달해주고 아니면 not access라고 전달 
 
    getRoles(user, onSuccess, onError) {
        setTimeout(() => {
            if (user === 'ellie') {
                onSuccess({ name: 'ellie', role: 'admin' });
            } else {
                onError(new Error('no access')); // 에러 'not 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);
    }
);
// 콜백함수를 많이쓰면 가독성이 떨어져 이해하기 어렵다. 
// 에러가 발생하거나 디버깅을 할때 너무 힘들어..짐 유지보수도 어려움
PreviousJavaScript PromiseNext자바스크립트 json

Last updated 4 years ago

Was this helpful?

콜백지옥체험

😱