
Callback review
function B() {
console.log('called at the back!');
}
function A(callback) {
callback; //callback == B
}
A(B);
Callback in Action: 반복 실행하는 함수(iterator)
[1,2,3].map(function(element, index) {
return element * element;
});
Callback in Action: 이벤트에 따른 함수(event handler)
document.querySelector('#btn').addEventListener('click', function(e) {
console.log('button clicked');
});
function handleClick() {
console.log('button clicked');
}
위의 함수를 연결하려고 하는 경우 당연히 함수 자체를 연결해야지 함수 실행을 연결해서는 안된다.
document.querySelector('#btn').onclick = handleClick;document.querySelector('#btn').onclick = function() { handleClick(); }document.querySelector('#btn').onlick = handleClick.bind();
위의 3개의 실행구문은 올바른 실행 구문이다.
하지만,
document.querySelector('#btn').onlick = handleClick();
위의 구문처럼 진행된다면 이벤트는 발생되지 않는다.
동기와 비동기
구분이 힘들다면? 카페에서 커피를 주문하는 모습을 관찰해보자.
// 현재 시각과 시작 시각을 비교하며 ms 범위 내에서 무한 루프를 도는 blocking 함수
function waitSync(ms) {
let start = Date.now();
let now = start;
while (now - start < ms) {
now = Date.now();
}
}
function drink(person, coffee) {
console.log(person + '는 ' + coffee + '를 마십니다');
}
function orderCoffeeSync(coffee) {
console.log(coffee + '가 접수되었습니다');
waitSync(4000);
return coffee;
}
let customers = [{
name: 'Steve',
request: 'Caffe Latte'
}, {
name: 'John',
request: 'Americano'
}];
// call synchronously
customers.forEach(function(customer) {
let coffee = orderCoffeeSync(customer.request);
drink(customer.name, coffee);
});
function waitAsync(callback, ms) {
setTimeout(callback, ms);
}
function drink(person, coffee) {
console.log(person + '는 ' + coffee + '를 마십니다');
}
let customers = [{
name: 'Steve',
request: 'Caffe Latte'
}, {
name: 'John',
request: 'Americano'
}];
function orderCoffeeAsync(menu, callback) {
console.log(menu + '가 접수되었습니다');
waitAsync(function() {
callback(menu);
}, 4000);
}
//call asynchronously
customers.forEach(function(customer) {
orderCoffeeAsync(customer.request, function(coffee) {
drink(customer.name, coffee);
});
});