[자바스크립트] 비동기 작업

J._NA 개발일지·2024년 5월 28일

비동기 작업(Asynchronous Task)이란?

  • 작업이 완료될 때까지 기다리지 않고, 즉시 다음 코드를 실행하는 방식의 작업을 의미
  • 프로그램의 흐름이 중단되지 않고 계속 진행될 수 있게 함.
  • 비동기 작업은 주로 네트워크 요청, 파일 읽기/쓰기, 타이머 등 시간이 걸릴 수 있는 작업에서 사용.

비동기 작업의 특징

  • 비차단(Non-blocking): 비동기 작업은 현재 실행 중인 작업을 멈추지 않고, 다른 작업을 계속 수행할 수 있게 함.
  • 콜백 함수: 비동기 작업이 완료된 후 실행할 코드를 콜백 함수로 전달함.
  • Promise와 async/await: 비동기 작업의 가독성을 높이기 위해 Promise와 async/await가 사용됨.

1. 콜백 함수 사용

console.log('Start');

setTimeout(() => {
    console.log('This is a delayed message');
}, 2000);

console.log('End');

2. Promise 사용

function asyncTask() {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve('Task completed');
        }, 2000);
    });
}

console.log('Start');
asyncTask().then((message) => {
    console.log(message);
});
console.log('End');

3. async/await 사용

function asyncTask() {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve('Task completed');
        }, 2000);
    });
}

async function executeAsyncTask() {
    console.log('Start');
    const message = await asyncTask();
    console.log(message);
    console.log('End');
}

executeAsyncTask();

4. 비동기 작업이 중요한 이유
비동기 작업을 통해 자바스크립트는 효율적으로 자원을 사용하고, 사용자의 인터페이스를 중단 없이 반응하게 할 수 있습니다. 특히 서버 요청이나 파일 읽기/쓰기 같은 시간이 많이 소요되는 작업에서, 비동기 작업은 사용자 경험을 크게 향상시킬 수 있습니다.

profile
아밥 & 프론트엔드 개발자

0개의 댓글