100일코딩챌린지 강의정리 javascript 5

하파타카·2023년 7월 1일
0

클래스

참고링크 - Classes mdn문서
객체를 생성하기 위한 템플릿으로, 특별한 함수의 일종이라고 생각하면 편하다.
기본개념은 자바의 클래스와 유사한듯.

class Job {
  constructor(jobTitle, place, salary) {
    this.title = jobTitle;
    this.location = place;
    this.salary = salary;
  }

  describe() {
    console.log(`I'm a ${this.title}, I work in ${this.location} and I earn ${this.salary}.`);
  }
}

const developer = new Job('Developer', 'New York', 45000);
const cook = new Job('Cook', 'Munich', 38000);
developer.describe();
cook.describe();
실행결과
I'm a Developer, I work in New York and I earn 45000.
I'm a Cook, I work in Munich and I earn 38000.

같은 유형의 객체를 여러개 생성할 때 객체를 생성하는 청사진으로 사용가능.
함수를 사용하듯 간단하게 객체생성을 할 수 있다.

비동기 코드

용량이 큰 파일을 로드한 후 다른 작업을 해야 하는경우 등 작업이 오래 걸리는 경우 순차적으로 처리하려면 대기시간이 지나치게 길어질 수 있다.
이때 오래 걸리는 작업을 비동기식으로 처리하는 방법을 생각해볼 수 있다.

비동기 란?
해당 라인의 작업이 완료되기 전 다음라인의 작업으로 넘어가는 것.

- async.js -

const fs = require('fs');

function readFile() {
  let fileData;

  fs.readFile('data.txt', function (error, fileData) {
    console.log('File parsing done!');
    console.log(fileData.toString());
  });

  console.log('Hi there!');
}

readFile();
실행결과
Hi there!
File parsing done!
텍스트 파일입니다.

→실행결과에서 텍스트 파일입니다.문구는 data.txt문서의 내용임.
뒤에 작성된 console.log('Hi there!');가 익명함수 function (error, fileData)의 실행보다 먼저인 이유는 익명함수를 비동기처리하여 data.txt를 읽는 도중에 아래의 코드가 먼저 실행 될 수 있는 경우 동기처리와는 달리 실행을 허용하였기 때문.
일반적인 경우 동기화되어 처리되므로 반드시 data.txt를 읽어온 다음에 console.log('Hi there!');부분이 실행된다.
Javascript의 특징과 연관하여 동기와 비동기에 대해 정확하게 익혀둘 것.

Promise

비동시 처리 시 문제점

  • 콜백함수에서 중첩된 함수를 처리할 경우(다수의 if블록이 겹쳐진 형태 등) 더욱 콜백함수에 종속적인 구조가 되어버릴 가능성이 있음.
  • 해당 작업의 결과가 나오지 않은 상태에서 다음행이 실행되어 가져올 결과값이 없어 오류가 발생할 수 있음.

콜백함수란?
미래의 어느 시점에서 실행될 다른 함수에 매개변수로 전달되는 함수

이때 promise를 사용하여 다음행이 현재 행의 결과를 요구할 때 결과를 보내겠다는 promies(약속)을 반환한다.
비동기 메서드에서 마치 동기 메서드처럼 반환이 가능한 것(이때 반환하는 것은 결과가 아닌 promise이다).

- async.js -

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

function readFile() {
  let fileData;

  // fs.readFile('data.txt', function (error, fileData) {
  //   console.log('File parsing done!');
  //   console.log(fileData.toString());
  // });

  fs.readFile('data.txt')
    .then(function (fileData) {
      console.log('File parsing done!');
      console.log(fileData.toString());
      // return anotherAsyncOperation;
    })
    .then(function () {});

  console.log('Hi there!');
}

readFile();

참고링크 - Promise mdn문서
참고링크 - 자바스크립트 Promise 쉽게 이해하기

비동기 작업 오류처리

비동기 작업은 작업이 시작되면 그 결과를 기다리지 않고 다음 작업에 들어가기 때문에 promise주위에 try-catch블록을 적용시키면 의도대로 돌아가지 않는다.
try-catch블록은 작업의 결과에 따라 선택적용되는데 비동기 코드는 결과를 확인하지 않기때문.

1) 콜백 작업의 경우

콜백 작업의 경우 오류를 알려주는 error매개변수를 이용한다.

if(error){
  // 에러발생 시 실행할 코드
}

2) promise 작업의 경우

.then()을 이용하듯 .catch()로 error매개변수를 이용.

- async.js -

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

function readFile() {
  let fileData;
  
  fs.readFile('data.txt')
    .then(function (fileData) {
      console.log('File parsing done!');
      console.log(fileData.toString());
      // return anotherAsyncOperation;
    })
    .then(function () {})
    .catch(function (error) {
      console.log(error);
    });

  console.log('Hi there!');
}

readFile();

async와 await

기본적으로는 promise의 사용을 더 용이하게 해주는 문법이다.

async

function의 앞에 사용되는 키워드.
async키워드를 적용하면 해당 함수는 항상 promise를 반환한다.
이때 반환될 것이 promise가 아닐 경우 promise로 감싸서 반환함.
즉, 코드의 외부적 모양이 동기함수인 듯 보여도 내부적으로는 비동기함수라고 이해하면 된다.

await

awaitasync함수에서만 동작한다. (일반함수에서 사용불가)

아래의 예제는 asyncawait를 적용하여 try-catch블록을 적용시킨 경우.
- async.js -

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

async function readFile() {
  let fileData;

  // fs.readFile('data.txt', function (error, fileData) {
  //   console.log('File parsing done!');
  //   console.log(fileData.toString());
  // });

  try {
    fileData = await fs.readFile('data.txt');
  } catch (error) {
    console.log(error);
  }
  console.log('File parsing done!');
  console.log(fileData.toString());
  // return anotherAsyncOperation;
  console.log('Hi there!');
}

readFile();

→실제동작은 위에서 .then을 사용했을때와 비슷하지만 코드만 봐서는 동기적처리를 하는 코드로 보인다. 그러므로 try-catch블록을 적용시킬 수 있는 것.


더 공부할 것

  • 객체 비구조화
  • 비동기식 작업처리
profile
천 리 길도 가나다라부터

0개의 댓글