[TIL] 19-09-23

|

callback함수

비동기 함수

blocking vs. non-blocking

전화와 문자로 비유할수 있음

동기 비동기

커피주문을 예로 들수 있다.

forEach함수

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);
    return coffee;
}

let customers = [{
    name: 'Steve',
    request: '카페라떼'
}, {
    name: 'John',
    request: '아메리카노'
}];

// call synchronosly
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 + '' + '를 마십니다');
}

let customers = [{
    name: 'Steve',
    request: '카페라떼'
}, {
    name: 'John',
    request: '아메리카노'
}];

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);
    });
});