비동기처리 콜백
2021. 5. 20. 22:06ㆍTIL/자바스크립트
728x90
// JavaScript is synchronous.
// Execute the code block in oreder 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 printWithDelay(print, timeout) {
setTimeout(print, timeout);
}
printWithDelay(() => console.log('async callbak'), 2000);
// Callback Hell example
class UserStorage {
loginUser(id, password, onSuccess, onError) {
setTimeout(()=> {
if (
(id === 'bella' && password === 'dream') ||
(id === 'coder' && password === 'academy')
) {
onSuccess(id);
} else {
onError(new Error('not found'));
}
}, 2000);
}
getRoles(user, onSuccess, onError) {
setTimeout(()=> {
if (user === 'bella') {
onSuccess({name: 'bella', role: 'admin'});
} else {
onError(new Error('no access'));
}
}, 1000);
}
}
const userStorage = new UserStorage();
const id = prompt('enter you id');
const password = prompt('enter you 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);
}
);
'TIL > 자바스크립트' 카테고리의 다른 글
callback to promise (0) | 2021.05.24 |
---|---|
Promise (0) | 2021.05.24 |
JSON (0) | 2021.05.20 |
Array API Quiz (0) | 2021.05.20 |
Array 배열 (0) | 2021.05.18 |