동기 호출 예시
function waitSync(ms) {
var start = Date.now();
var now = start;
while(now - start < ms) {
now = Date.now();
}
} // 현재 시각과 시작 시각을 비교하여 ms 범위 내에서 무한 루프를 도는 blocking 함수
function drink(person, coffee) {
console.log(person + '는 ' + coffee + '를 마십니다')
}
function orderCoffeeSync(coffee) {
console.log(coffee + '가 접수되었습니다');
waitSync(2000); //2초동안 blocking 시킨다..!!!
return coffee;
}
let customers = [{
name: 'Mindy',
request: 'Cafe Latte'
}, {
name: 'Jay',
request: 'Americano'
}];
//call synchronously
customers.forEach(function(customer){
let coffee = orderCoffeeSync(customer.request);
drink(customer.name, coffee);
});
비동기 호출 예시
function waitAsync(callback, ms) {
setTimeout(callback, ms);
} // 특정 시간 이후에 callback 함수가 실행되게끔 하는 브라우저 내장 기능.
function drink(person, coffee) {
console.log(person + '는 ' + coffee + '를 마십니다')
}
let customers = [{
name: 'Mindy',
request: 'Cafe Latte'
}, {
name: 'Jay',
request: 'Americano'
}];
function orderCoffeeAsync(menu, callback) {
console.log(menu + '가 접수되었습니다');
waitAsync(function() {
callback(menu);
}, 4000);
}
//call synchronously
customers.forEach(function(customer){
orderCoffeeAsync(customer.request, function(coffee) { //2번째 인자로 callback 함수)
drink(customer.name, coffee);
});
});
1. Mindy가 cafe latte를 주문한다(orderCoffeeAsync) => waitAsync(callback(cafe latte), 4초)
2. Jay가 Americano를 주문한다(orderCoffeeAsync) => waitAsync(callback(Americano), 4초)
3. 4초가 지났고, function(coffee){ drink (Mindy, Cafe Latte)} 가 실행된다.
4. 4초가 지났고, function(coffee){ drink (Jay, Americano)} 가 실행된다.
브라우저의 비동기 함수 작동 원리가 궁금하다면?
Event Loop: developer.mozilla.org/ko/docs/Web/JavaScript/EventLoop
Philip Roberts: I'm stuck in an event loop => youtube(youtu.be/6MXRNXXgP_0)
'BootCamp_Codestates > Pre Tech Blog' 카테고리의 다른 글
런타임 node.js (0) | 2020.12.02 |
---|---|
spread syntax VS rest parameter (0) | 2020.11.27 |
알고리즘 - 수도코드 작성법 (0) | 2020.11.10 |
고차함수(Higher Order Function) (0) | 2020.11.10 |
Closure (0) | 2020.11.08 |