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