nika-blog

JS의 동기와 비동기 본문

FE/JS

JS의 동기와 비동기

nika0 2021. 8. 30. 10:05

안녕하세요. 

오늘은 동기와 비동기 코드 작성에 대한 포스팅을 하려고 합니다. 

 

백엔드에서 사용자 데이터 등을 받아올 때, 비동기적 프로그래밍은 꼭 필요한데요 

개념부터 살펴볼까요?

 

 

1. 동기와 비동기 개념

  • 동기 방식 : A작업이 모두 진행 될때까지 B작업은 대기해야한다.
  • 비동기 방식 : A작업이 시작하면 동시에 B작업이 실행된다. A작업은 결과값이 나오는대로 출력된다.

자바스크립트는 동기적으로 작동합니다. 

하지만 비동기적으로 코드를 작성할 수도 있습니다. 

바로 콜백함수를 사용하는 것인데요, 여기서는 setTimeOut 함수로 구현할 수 있을 것 같습니다. 

 

setTimeOut.js
'use strict';

//JavaScript is synchronous.
//Execute the code block by order after hoisting.
//hoisting: var, function declaration

console.log('1');
setTimeout(() => console.log('2'), 1000);
console.log('3');

 

synchronous.js
//synchronous callback
const printImmediately = (print) => print();
printImmediately(() => console.log('synchronous'));

 

asynchronous.js

//Asynchronous callback
const printWithDelay = (print, timeout) => setTimeout(print, timeout);
printWithDelay(() => console.log('async callback'), 2000);

 

하지만 비동기 프로그래밍을 위해 콜백함수를 난발하면, 콜백지옥이 형성될 수도 있는데요

콜백지옥은 가독성이 좋지 않아서 개발자가의 코드 유지보수가 힘들 뿐 아니라

나쁜 코드이므로 지양해야 합니다. 

 

콜백지옥에서 탈출할 수 있는 promise는 다음 포스팅으로 가져와 보겠습니다. 

'FE > JS' 카테고리의 다른 글

JS - DOM 조작  (0) 2022.02.20
프로미스(Promise)  (0) 2021.09.01
JSON(Javascript Object Notation)  (0) 2021.08.29
콘솔(console) 잘 사용하는 법  (0) 2021.08.23
JS 좋은 코드에 대한 고민 - 1  (0) 2021.08.20