typescript

자바스크립트 11. 비동기 처리의 시작 콜백 이해하기, 콜백 지옥 체험 😱 JavaScript Callback

JJIMJJIM 2020. 7. 2. 08:45
728x90
반응형
SMALL

'use strict';

// javascript is synchronous. 동기적이다.
// Execute the code block by order after hoisting. 호이스팅 된 이후부터 작성한 순서에 맞춰 하나하나 동기적으로 실행된다.
// hoisting: var, function declaration 함수 선언들이 자동으로 제일 위로 올라가는 것

console.log(1);
setTimeout(() => console.log(2), 1000)
console.log(3);

// Synchronous callback 즉각적으로 동기적으로 실행
function printImmediately(print) {
	print();
}
printImmediately(() => console.log('hello'));

// Asynchronous callback 나중에 언제 실행될지 예측할수 없는 콜백
function printWidthDelay(print, timeout) {
	setTimeout(print, timeout);
}
printWidthDelay(() => console.log('async callback'), 2000);


// Callback Hell example
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('enter your id');
const password = prompt('enter your password');
userStorage.loginUser(
id, 
password, 
user => {
	userStorage.getRole(
		user, 
		userWithRole => {
			alert(`Hello ${userWithRole.name}, you have a ${userWithRole.role} role`)	
		}, 
		error => {
			console.log(error);
		}
	);
}
error => {
	console.log(error);
}
);

https://www.youtube.com/watch?v=s1vpVCrT8f4

 

728x90
반응형
LIST