'use strict'
//var선언이나 function같은것들을 선언하면 자동적으로 가장위에서 선언된것처럼 되는것을 호이스팅이라고 한다.
console.log('1');
setTimeout(()=>{console.log("2")},1000); //callback함수를 n초 후에 실행시켜줘
console.log('3');
//Synchronous callback
function printImmediately(print){
print();
}
printImmediately(()=>{console.log('hello')});
//Asynchronous callback
function printWithDelay(print,timeout){
setTimeout(print,timeout);
}
printWithDelay(()=>console.log('async callback'),2000);
//콜백 지옥 예제 만들어보기
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.getRoles(
user,
userWithRole=>{
alert(`hello ${userWithRole.name}, you have a ${userWithRole.role} role`)
},
error =>{console.log(error)})
}
,(error)=>{console.log(error)}
);
콜백지옥..이해가너무힘들다..
'JS > 드림코딩앨리' 카테고리의 다른 글
13. 비동기의 꽃 JavaScript async 와 await 그리고 유용한 Promise APIs (0) | 2021.04.22 |
---|---|
12. 프로미스 개념부터 활용까지 JavaScript Promise (0) | 2021.04.22 |
10. JSON 개념 정리 와 활용방법 (0) | 2021.04.21 |
9. 유용한 10가지 배열 함수들. Array APIs 총정리 (0) | 2021.04.21 |
8. 배열 제대로 알고 쓰자. 자바스크립트 배열 개념과 APIs 총정리 (0) | 2021.04.21 |