'use strict';
JavaScript is synchronous. (동기적_작성순서에 따름)
Execute the code block by orger after hoisting.
hoisting: var, function declaration (함수 선언들이 자동적으로 가장 위로 올라감 / 코드순서대로 실행)
console.log('1'); //1
//지정한 시간이 지나면 callback함수 호출
setTimeout(function(){
console.log('2');
},1000); //1초 후 browser가 출력
//간략히
setTimeout(()=> console.log('2'),1000);
console.log('3');
//1,3,2
Synchronous callback
function printImmediately(print){
print();
}
printImmediately(()=>console.log('hello')); //hello
//1,3,hello,2
Asynhronous callback
function printWithDelay(print, timeout){
setTimeout(print, timeout);
}
printWithDelay(()=>console.log('async callback'),2000); //async callback
//1,3,2,async callback
Callback Hell example
1. 가독성,이해력저하
2. error, debugging 처리 난해
class UserStorage{
loginUser(id, password, onSuccess, onError){
setTimeout(()=>{
if(
(id === 'ellie' && password === 'dream') || //or
(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=>{
alert(`Hello ${userWithRole.name}, you have a ${userWithRole.role} role`);
},
error => {
console.log(error);
}
);
},
error=>{console.log(error)}
);
반응형
'JS > [드림코딩] 엘리 (완)' 카테고리의 다른 글
13강. async, await, promise APIs (0) | 2020.08.24 |
---|---|
12강. Promise (0) | 2020.08.15 |
10강. JSON (0) | 2020.07.20 |
09강. Array APIs (0) | 2020.07.20 |
08강. Array (0) | 2020.07.11 |