Day 55: Asynchronous Call

1. TIL (Today I Learned)

Callback Review

A function that is passed as a parameter to another function.
A function that receives a parameter can execute the callback function immediately(synchronously) or later(asynchronously) as needed.

function B() {
  console.log('called at the back!');
  }
  
function A(callback) {
  callback(); // callback === B
  }

callback in action: function to run repeatedly(iterator)

[1, 2, 3].map(function(element, index) {
  return element * element;
});

callback in action: function according to the event(event handler)

document.querySelector('#btn').addEventListener('click', function(e) {
  console.log('button clicked');
  });
 

Don't get confused!

function handleClick() {
  console.log('button clicked');
  };

Correct Answers:

document.querySelector('#btn').onclick = handleClick;
document.querySelector('#btn').onclick = function () {
handleClick()
}
document.querySelector('#btn').onclick = handleClick.bind();

Wrong Answers:

document.querySelector('#btn').onclick = handleClick();
** It's not about linking function execution. Link the function itself.

Blocking vs. Non-Blocking

Phone Call
1. You have to stop what you're doing and receive a new call(blocking).
Text message
1. After checking the text, you can reply later (non-blocking).
Phone Call
2. The result of the request happens at the same time (synchronous).
Text Message
2. The results fo the requests do not occur at the same time. (asynchronous)

Synchronous & Asynchronous in Coffee Ordering

Synchronous

  • The result of the request happens at the same time.

What if coffee orders work synchronously?
1. Customer 1 orders an Americano.
2. The staff brews the Americano.
3. The staff delivers an Americano to Customer 1.
4. Customer 2 orders an cafe latte.
5. The staff starts making the cafe latte.
6. The employee delivers a cafe latte to Customer 2.

** Guest 2 can't even order and has to stay in the queue until Guest 1 gets their Americano delivered.

Asynchronous

  • The results of the request do not occur at the same time.
  1. Customer 1 orders an Americano.
    1. The staff starts brewing the Americano.
    2. When the Americano is finished, the staff calls Customer 1.
    3. Deliver the Americano to Customer 1.
  2. Customer 2 orders an Cafe Latte.
    1. The staff starts making a Cafe Latte.
    2. When the Cafe Latte is finished, the staff calls Customer 2.
    3. Deliver the Cafe Latte to Customer 2.
  • There is no blocking in the request.
  • Responses are made asynchronously.
  • "is finished" is an event.
  • staff calling the customer is a callback.

Asynchronous function passing pattern 1: callback pattern

let request = 'cafe latte';
orderCoffeeAsync(request, function(response) {
// response --> coffee order result
drink(response);
});

Asynchronous function passing pattern 2: event registration pattern

let request = 'cafe latte';
orderCoffeeAsyn(request).onready = function(response) {
// response --> coffee order result
drink(response);
});

Key Examples of Async

DOM Element event handlers
- Mouse and keyboard input(click, keydown, etc.)
- Page loading (DOMcontentLoaded etc.
Timer
- Timer API (setTimeout, etc.)
- Animation API (requestAnimationFrame)
Requesting and Responsing resources from/to the server.
- fetch API
- AJAX (XHR)

Examples of Synchronous and Asynchronous Coffee order in JavaScript.

Synchronous Coffee Order

function waitSync(ms) {
  var start = Date.now();
  var now = start;
  while (now - start < ms) {
    now = Date.now();
    }
  }
  
function drink(person, coffee) {
  console.log(person + 'is drinking' + coffee);
  }
  
function orderCoffeeSync(coffee) {
  console.log(coffee + 'is ready.');
  waitSync(4000);
  return coffee;
}

let customers = [{
  name: 'Steve',
  request: 'cafe latte'
  }, {
  name: 'John',
  request: 'Americano'
  }];
  
// call synchronously
customers.forEach(function(customer) {
  let coffee = orderCoffeeSync(customer.request);
  drink(customer.name, coffee);
});

Asynchronous Coffee Order

function waitAsync(callback, ms) {
  setTimeout(callback, ms);
  }
  
function drink(person, coffee) {
  console.log(person + 'drinks' + coffee);
  }
  
let customers = [{
  name: 'Steve',
  request: 'cafe latte'
  }, {
  name: 'John',
  request: 'americano'
  }];
  
function orderCoffeeAsync(menu, callback) [
  console.log(menu + 'is ready');
  waitAsync(function() {
    callback(menu);
    }, 4000);
  }
  
// call asynchronously

customers. forEach(function(customer) {
  orderCoffeeAsync(customer.request, function(coffee) {
  drink (customer.name, coffee);
  });
});

2. 3 Things to be Thankful for

  1. Thankful for God reminding me that He is the maker of everything and hold on to my super super small and evil faith.
  2. Thank God for reminding me that I have to stay humble and just do my daily chores with all my heart.
  3. Thank God for guiding my loved ones and my family throughout the day.

3. Ideas and Things to Think About.

  1. All you need to do is just work hard with all your heart and never burden yourself with worries that makes yourself doubt God's strength. Always remember what He has done for you till today and never forget the blessings.

좋은 웹페이지 즐겨찾기