Callback과 비동기 호출

마데슾 : My Dev Space·2019년 10월 17일
0

[CODESTATES]PRE

목록 보기
19/19

call back

  • 다른 함수(A)의 전달인자(argument)로 넘겨주는 함수(B)
  • parameter를 넘겨받는 함수(A)는 callback 함수(B)를 필요에 따라 즉시 실행할수도 있고, 아니면 나중에 실행할 수도 있다.
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(elem, index) {
      return elem * index;
    });
  • callback in action : 이벤트에 따른 함수(event handler)
      document.querySelector('#btn').addEventListener('click', function(e) {
        console.log('button clicked');
      })

    동기 vs 비동기

    동기

    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 synchronously
customers.forEach(function(customer) {
let coffee = orderCoffeeSync(customer.request);
drink(customer.name, coffee);
});

#### 비동기
```js
function waitAsync(callback, ms) {
 setTimeout(callback, ms); // 특정 시간 이후에 callback 함수가 실행되게끔 하는 브라우저 내장 기능입니다
}

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: '아메리카노'
}];

function orderCoffeeAsync(menu, callback) {
 console.log(menu + '가 접수되었습니다');
 waitAsync(function() {
   callback(menu);
 }, 2000);
}

// call asynchronously
customers.forEach(function(customer) {
 orderCoffeeAsync(customer.request, function(coffee) {
   drink(customer.name, coffee);
 });
});
profile
👩🏻‍💻 🚀

0개의 댓글