kingsubin

10. Callback 본문

JavaScript & TypeScript

10. Callback

kingsubin 2020. 11. 15. 14:28

 

  • JavaScript is synchronous
  • Execute the code block in order after hoisting
  • hoisting : var, function declaration
console.log('1');
setTimeout(() => console.log('2'), 1000);
console.log('3'); 
// 1, 3, 2

 

 

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 Hell 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');
userStroage.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)});

 

 

 

 

 


※출처

www.youtube.com/channel/UC_4u-bXaba7yrRz_6x6kb_w

'JavaScript & TypeScript' 카테고리의 다른 글

React - 시작하기  (0) 2020.11.23
11. Promise  (0) 2020.11.15
9. JSON  (0) 2020.11.15
8. Array APIs  (0) 2020.11.14
7. Array, API  (0) 2020.11.14
0 Comments
댓글쓰기 폼