2021. 9. 13
© WONKOOK LEE
자바스크립트의 비동기 처리와 AJAX, API 개념의 이해
동기(Synchronous)와 비동기(Asynchronous)
동기적 작동이란 무엇일까?
- 대부분의 코드는 동기적으로 작동한다. Most code is synchronous.
- 동기적인 코드는 순서대로 작동한다. Synchronous code is executed line by line.
- 동기적인 코드는 순서대로 작동하기 때문에 이전 코드의 실행이 끝나야 다음 코드가 작동한다. Each line of code waits for previous line to finish.
- 동작을 마칠 때 까지 시간이 소요되는 특정 코드가 다른 코드의 실행을 막을 수 있다. Long-running operations block code execution.
Blocking of Synchronous Code
const body = document.body;
body.textContent = "My name is Wonkook!";
window.alert("Blocking Code Execution!"); // Blocking
body.textContent = "My name is Kiwi!";
위 코드가 어떻게 동작할 지 생각해보자.
기본적으로 코드는 동기적으로, 순서대로 실행되고 이전 코드가 끝나지 않으면 다음 코드가 실행되지 않는다.
두번째 행의 코드로 인해 제일 먼저 body
의 텍스트가 'My name is Wonkook!'으로 바뀌게 된다.
세번째 행에서 alert 창이 발생되는데, 이 창을 끄지 않으면 다음 코드가 작동하지 않는다.
alert를 닫으면 비로소 다음 코드가 작동되고, body
에 출력되는 텍스트가 'My name is Kiwi!'로 바뀌게 된다.
여기서 blocking code는 바로 alert 함수가 된다.