callback.js
'use strict'
//Synchronous callback
function printImmediately(print){
print();
}
//Asynchronous callback
function printWithDelay(print, timeout) {
setTimeout(print, timeout);
}
//JavaScript is synchronouse.
//Execute the code block by orger after hoisting.
//hoisting: var, funcition declaration
console.log('1');
setTimeout(() => console.log('2'), 1000);
//console.log('2');
console.log('3');
printImmediately(() => console.log('hello'));
printWithDelay(() => console.log('async callback'), 2000);
//Callback Hell example
class UserStorage {
loginUser(id, password, onSuccess, onError) {
setTimeout(()=> {
if(
(id === 'june' && password === 'young') ||
(id === 'coder' && password === 'academy')
){
onSuccess(id);
}else{
onError(new Error('not found'));
}
}, 2000);
}
getRoles(user, onSuccess, onError){
setTimeout(() => {
if(user === 'june'){
onSuccess({name: 'june', 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)}
);
'프론트엔드 > 바닐라 자바스크립트' 카테고리의 다른 글
자바스크립트 콜백 Callback함수 알아보기 (0) | 2022.03.06 |
---|---|
자바스크립트 배열 개념과 APIs (0) | 2021.12.07 |