프로그래밍/Node.js

[Node.js 강의 시리즈] 5강 - Node.js의 비동기 처리

월횽 2024. 6. 28. 06:30
728x90
반응형
SMALL

비동기 프로그래밍의 개념을 이해하고, Node.js에서 비동기 처리를 위해 사용하는 콜백 함수, 프로미스, async/await를 학습한다.

 

 

 

 

 

1. 비동기 프로그래밍의 개념

 

비동기 프로그래밍이란?

· 비동기 프로그래밍은 코드 실행이 블록되지 않고, 특정 작업이 완료될 때까지 기다리지 않으며, 그동안 다른 작업을 수행할 수 있는 프로그래밍 방식이다.
· Node.js는 단일 스레드로 동작하기 때문에, 비동기 프로그래밍을 통해 I/O 작업(파일 읽기/쓰기, 네트워크 요청 등)을 효율적으로 처리할 수 있다.

 

동기 vs 비동기

· 동기(Synchronous): 코드가 순차적으로 실행되며, 각 작업이 완료될 때까지 다음 작업을 시작하지 않는다.
· 비동기(Asynchronous): 작업이 시작되면 다음 작업을 바로 시작하며, 작업이 완료되면 콜백 함수 등을 통해 결과를 처리한다.

 

 

반응형

 

 

2. 콜백 함수

 

콜백 함수란?

· 콜백 함수는 다른 함수의 인수로 전달되어, 특정 작업이 완료된 후 호출되는 함수이다.
· Node.js의 비동기 API 대부분은 콜백 함수 형태로 제공된다.



콜백 함수 예제

const fs = require('fs');

fs.readFile('example.txt', 'utf8', (err, data) => {
  if (err) {
    console.error('Error reading file:', err);
    return;
  }
  console.log('File content:', data);
});

console.log('This will be logged first');

 

 

 

 

 

3. 프로미스 (Promise)

 

프로미스란?

· 프로미스는 비동기 작업의 완료 또는 실패를 나타내는 객체이다.
· then, catch, finally 메서드를 통해 비동기 작업의 결과를 처리할 수 있다.

728x90

프로미스 예제

const fs = require('fs').promises;

fs.readFile('example.txt', 'utf8')
  .then(data => {
    console.log('File content:', data);
  })
  .catch(err => {
    console.error('Error reading file:', err);
  });

console.log('This will be logged first');

 

 

프로미스 생성

const myPromise = new Promise((resolve, reject) => {
  const success = true; // 예제이므로 임의로 설정

  if (success) {
    resolve('Operation was successful');
  } else {
    reject('Operation failed');
  }
});

myPromise
  .then(result => {
    console.log(result);
  })
  .catch(error => {
    console.error(error);
  });

 

 

 

 

 

4. async/await

 

async/await란?

· async/await는 ES8(ES2017)에서 도입된 비동기 작업을 처리하는 새로운 방법이다.
· 프로미스를 사용한 비동기 코드를 더 간결하고 가독성 있게 작성할 수 있다.

 

async/await 예제

const fs = require('fs').promises;

async function readFile() {
  try {
    const data = await fs.readFile('example.txt', 'utf8');
    console.log('File content:', data);
  } catch (err) {
    console.error('Error reading file:', err);
  }
}

readFile();

console.log('This will be logged first');

 

 

 

 

 

 

async 함수

· async 키워드를 함수 앞에 붙여서 해당 함수를 비동기로 만든다.
· await 키워드는 프로미스가 해결될 때까지 함수의 실행을 일시 중지시킨다. await는 async 함수 내에서만 사용할 수 있다.

 

 

 

 

 

- 이전 수업 목록

 

 

 

728x90
반응형
LIST