VIDEO
동영상 수강 전 본문 내용 스캔.
동영상 수강 후 본문 내용 스캔.
안 보고 직접 코드 타이핑 하기.
1. 동기 vs 비동기
'use strict';
// Javascript is syncronous.
// Execute the code block in order after hoisting.
// hoisting : var, function declaration
// synchronous (1 → 2 → 3)
console.log('1');
console.log('2');
console.log('3');
// asynchronous (1 → 3 → 2)
console.log('1');
/*
setTimeout(function () { // 브라우저에게 1초후 콜백함수 호출 맡기고, 먼저 3 출력.
console.log('2');
}, 1000);
*/
setTimeout(() => console.log('2'), 1000); // 화살표함수 사용해 더 간단히 표현.
console.log('3');
// Synchronous callback (1 → 3 → hello → 2)
// 함수 선언은 hoisting 되므로, 'use strict' 코드 바로 밑으로 올린 상태로 인식.
function printImmediately(print) {
print();
}
printImmediately(() => console.log('hello'));
// Asynchronous callback (1 → 3 → hello → 2 → async callback)
// 함수 선언은 hoisting 되므로, 위 함수 선언 밑으로 올린 상태로 인식.
function printWithDelay(print, timeout) {
setTimeout(print, timeout);
}
printWithDelay(() => console.log('async callback'), 2000);
PS. 위 코드는 실제로는 아래처럼 작동.
'use strict';
function printImmediately(print) {
print();
}
function printWithDelay(print, timeout) {
setTimeout(print, timeout);
}
// Javascript is syncronous.
// Execute the code block in order after hoisting.
// hoisting : var, function declaration
// synchronous (1 → 2 → 3)
console.log('1');
console.log('2');
console.log('3');
// asynchronous (1 → 3 → hello → 2 → async callback)
console.log('1');
setTimeout(() => console.log('2'), 1000); // 화살표함수 사용해 더 간단히 표현.
console.log('3');
printImmediately(() => console.log('hello'));
printWithDelay(() => console.log('async callback'), 2000);
2. 콜백 지옥
// 콜백 지옥 : 콜백함수를 안긴 형태로 중첩적으로 호출하는 형태로 짠 코드
// 문제점: 유지보수 어려움 (∵ 1. 가독성 저하 2. 디버깅 곤란.)
// Callback Hell example
class UserStorage {
loginUser(id, passwod, 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.getRoles(
user,
(userWithRole ) => {
// userWidthRole는 { name: 'ellie', role: 'admin' } 객체 가리키는 임의의 매개변수임.
alert(`Hello ${userWithRole .name}, you have a ${userWithRole .role} role`);
// 결과값 : Hello ellie , you have a admin role
// alert(`Hello ${user .name}, you have a ${user .role} role`);
// 결과값 : Hello undefined , you have a undefined role
},
(error) => {
console.log(error);
}
);
},
(error) => {
console.log(error);
}
);
주소 복사
랜덤 이동
최신댓글