[F-Lab 모각코 챌린지-20일차] - asynchronous

Big One·2023년 5월 30일
0

F-Lab

목록 보기
67/69

비동기 프로그래밍이란?

작업이 완료될 때까지 기다리지 않고 잠재적으로 오래 실행되는 작업을 실행하여 해당 작업이 실행되는 동안에도 다른 이벤트에 응답할 수 있게 하는 기술이다. 작업이 완료되면 결과를 제공한다.

필요한 이유

동기 프로그래밍으로 코드를 작성할 경우 블로킹 연산이 될 때 다른 이벤트에 응답할 수 없어 페이지가 멈추는 현상이 발생한다. 아래 코드로 비교해보장

동기 프로그래밍

<label for="quota">Number of primes:</label>
<input type="text" id="quota" name="quota" value="1000000">

<button id="generate">Generate primes</button>
<button id="reload">Reload</button>

<div id="output"></div>
function generatePrimes(quota) {

  function isPrime(n) {
    for (let c = 2; c <= Math.sqrt(n); ++c) {
      if (n % c === 0) {
          return false;
       }
    }
    return true;
  }

  const primes = [];
  const maximum = 1000000;

  while (primes.length < quota) {
    const candidate = Math.floor(Math.random() * (maximum + 1));
    if (isPrime(candidate)) {
      primes.push(candidate);
    }
  }

  return primes;
}

document.querySelector('#generate').addEventListener('click', () => {
  const quota = document.querySelector('#quota').value;
  const primes = generatePrimes(quota);
  document.querySelector('#output').textContent = `Finished generating ${quota} primes!`;
});

document.querySelector('#reload').addEventListener('click', () => {
  document.location.reload()
});

generatePrimes() 함수가 실행 중인 동안 프로그램이 완전히 응답하지 않는 것을 확인할 수 있고, 아무것도 입력할 수 없고 클릭도 안되며, 그 외 다른 것도 할 수 없다.

우리는 이러한 프로그램보단 함수가 실행되는 동안에도 다른 작업을 할 수 있는 것을 원한다.

이벤트 처리기는 비동기 프로그래밍의 한 형태이다. 아래는 이벤트 처리기로 작성한 비동기 방식이다.

<button id="xhr">Click to start request</button>
<button id="reload">Reload</button>

<pre readonly class="event-log"></pre>
const log = document.querySelector('.event-log');

document.querySelector('#xhr').addEventListener('click', () => {
  log.textContent = '';

  const xhr = new XMLHttpRequest();

  xhr.addEventListener('loadend', () => {
    log.textContent = `${log.textContent}Finished with status: ${xhr.status}`;
  });

  xhr.open('GET', 'https://raw.githubusercontent.com/mdn/content/main/files/en-us/_wikihistory.json');
  xhr.send();
  log.textContent = `${log.textContent}Started XHR request\n`;});

document.querySelector('#reload').addEventListener('click', () => {
  log.textContent = '';
  document.location.reload();
});
// 결과
Started XHR request
Finished with status: 200

결과를 보면 이벤트 처리기(비동기)가 끝날때 까지 기다리지 않고 이벤트 처리기가 실행되는 도중에 다른 이벤트가 처리되는 것을 볼 수 있다.

profile
이번생은 개발자

0개의 댓글