콜백 기반 비동기 함수 프로미스화

JavaScriptBeginner
지금 연습하기

소개

이 프로젝트에서는 JavaScript 에서 콜백 기반 비동기 함수를 프로미스화하는 방법을 배우게 됩니다. 특히, Node.js 의 fs 모듈에 있는 콜백 기반 readFile 함수를 프로미스 기반 버전으로 변환할 것입니다.

🎯 과제

이 프로젝트에서 다음을 배우게 됩니다:

  • 함수를 프로미스화하기 위한 조건을 식별하는 방법
  • 콜백 기반 함수를 래핑하고 프로미스를 반환하는 promisefy 함수를 구현하는 방법
  • readFile 함수의 프로미스 기반 버전을 사용하여 파일을 비동기적으로 읽는 방법

🏆 성과

이 프로젝트를 완료하면 다음을 수행할 수 있습니다:

  • 콜백 기반 비동기 프로그래밍보다 프로미스를 사용하는 이점을 이해합니다.
  • 콜백 기반 함수를 프로미스 기반 함수로 변환하는 일반적인 promisefy 함수를 구현합니다.
  • 코드 가독성과 오류 처리를 개선하기 위해 자체 프로젝트에서 프로미스 기반 비동기 함수를 활용합니다.

readFile 함수 프로미스화

이 단계에서는 Node.js 의 fs 모듈에서 readFile 함수를 프로미스화하는 방법을 배우게 됩니다. 이 단계를 완료하려면 아래 단계를 따르세요:

  1. 코드 편집기에서 index.js 파일을 엽니다.
  2. 파일 상단에서 필요한 모듈을 require 합니다:
const fs = require("fs");
const path = require("path");
  1. test-promisefy.json 파일의 파일 경로를 정의합니다:
const textPath = path.join(__dirname, "/test-promisefy.json");
  1. promisefy 함수를 구현합니다:
const promisefy = (fn) => {
  return (textPath, type) => {
    return new Promise((resolve, reject) => {
      fn(textPath, type, (err, contrast) => {
        if (err) {
          reject(err);
        } else {
          resolve(contrast);
        }
      });
    });
  };
};

promisefy 함수는 콜백 기반 함수 fn을 인수로 받아 프로미스를 반환하는 새로운 함수를 반환합니다. 반환된 함수는 원래의 fn 함수를 호출하고, 결과로 프로미스를 resolve 하거나 오류로 reject 합니다.

  1. promisefy 함수를 사용하여 readFile 함수의 프로미스 기반 버전을 생성합니다:
const readFileSync = promisefy(fs.readFile);

이제 readFileSync 함수를 사용하여 프로미스를 통해 test-promisefy.json 파일을 비동기적으로 읽을 수 있습니다.

✨ 솔루션 확인 및 연습

프로미스 기반 readFile 함수로 파일 읽기

이 단계에서는 프로미스 기반 readFileSync 함수를 사용하여 test-promisefy.json 파일을 읽는 방법을 배우게 됩니다.

  1. index.js 파일에 다음 코드를 추가합니다:
fs.readFile(textPath, "utf8", (err, contrast) => {
  const readFileSync = promisefy(fs.readFile);

  readFileSync(textPath, "utf8")
    .then((res) => {
      console.log(res === contrast); // The result here is expected: true, i.e. the promise returns the same content as the previous read.
    })
    .catch((err) => {});
});

이 코드는 파일 경로와 인코딩을 사용하여 readFileSync 함수를 호출한 다음, thencatch 메서드를 사용하여 프로미스 해결 및 거부를 처리합니다.

  1. 이제 index.js 파일은 다음과 같아야 합니다:
const fs = require("fs");
const path = require("path");
const textPath = path.join(__dirname, "/test-promisefy.json");

fs.readFile(textPath, "utf8", (err, contrast) => {
  const readFileSync = promisefy(fs.readFile);

  readFileSync(textPath, "utf8")
    .then((res) => {
      console.log(res === contrast); // The result here is expected: true, i.e. the promise returns the same content as the previous read.
    })
    .catch((err) => {});
});

const promisefy = (fn) => {
  return (textPath, type) => {
    return new Promise((resolve, reject) => {
      fn(textPath, type, (err, contrast) => {
        if (err) {
          reject(err);
        } else {
          resolve(contrast);
        }
      });
    });
  };
};

module.exports = promisefy;
  1. 터미널에서 index.js 파일을 실행합니다:
node index

true 출력을 볼 수 있습니다. 이는 프로미스 기반 readFile 함수가 원래 콜백 기반 readFile 함수와 동일한 내용을 반환했음을 의미합니다.

축하합니다! readFile 함수를 성공적으로 프로미스화하고 프로미스 기반 버전을 사용하여 파일을 읽었습니다.

✨ 솔루션 확인 및 연습

요약

축하합니다! 이 프로젝트를 완료했습니다. LabEx 에서 더 많은 랩을 연습하여 기술을 향상시킬 수 있습니다.