반응형
Notice
Recent Posts
Recent Comments
Link
동캄의 코딩도장
JS [call back] 본문
반응형
'use strict';
// JavaScript is synchronous.
// Excute the coe block by order after hoisting.
// hoisting: var, function declaration
setTimeout(()=> console.log('2'),1000)
// 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);
// Callback kHell example
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);});
반응형
'front > HTML&CSS&JS' 카테고리의 다른 글
JS [callback-to-promise 예제] (0) | 2022.01.25 |
---|---|
JS [promise] (0) | 2022.01.25 |
JS [JSON] (0) | 2022.01.25 |
JS [array API] (0) | 2022.01.24 |
JS [array] (0) | 2022.01.24 |