header-img
Info :
728x90
  1. 'part-2/02_promiseConstructor.js' ํŒŒ์ผ์„ ๊ตฌํ˜„ํ•˜๊ณ , ํ…Œ์ŠคํŠธ๋ฅผ ํ†ต๊ณผํ•ฉ๋‹ˆ๋‹ค. callback์ด๋ผ๋Š” ๋งค๊ฐœ๋ณ€์ˆ˜(parameter) ๋Œ€์‹ , Promise์˜ resolve, reject ํ•จ์ˆ˜๋ฅผ ์ด์šฉํ•˜์„ธ์š”.
  2. part-2/03_basicChaining.js์€, ์•ž์„œ ์ž‘์„ฑํ•œ getDataFromFilePromise๋ฅผ ์ด์šฉํ•ด์„œ ํ’€์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.
    • fs ๋ชจ๋“ˆ์„ ์ง์ ‘ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์ด ์•„๋‹™๋‹ˆ๋‹ค.
    • getDataFromFilePromise๋ฅผ ์ด์šฉํ•ด, 'files/user1.json' ํŒŒ์ผ๊ณผ 'files/user2.json' ํŒŒ์ผ์„ ๋ถˆ๋Ÿฌ์˜ค๊ณ , ๋‘ ํŒŒ์ผ์„ ํ•ฉ์ณ์„œ ์ตœ์ข…์ ์œผ๋กœ ๋‘ ๊ฐ์ฒด๊ฐ€ ๋‹ด๊ธด ๋ฐฐ์—ด์„ ๋งŒ๋“œ๋Š” ๊ฒƒ์ด ๋ชฉํ‘œ์ž…๋‹ˆ๋‹ค.
      • ํŒŒ์ผ ๊ฒฝ๋กœ๋ฅผ ์ฐพ์„ ๋•Œ, user1Path ๋ฐ user2Path๋ฅผ ์ด์šฉํ•˜์„ธ์š”.
    • then์ด ์–ด๋–ค ๋งค๊ฐœ๋ณ€์ˆ˜๋ฅผ ์ „๋‹ฌ๋ฐ›๋Š”์ง€์— ๋Œ€ํ•œ ์ดํ•ด๊ฐ€ ์žˆ์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.
    • then์˜ ๋ฆฌํ„ด์ด ๋ฌด์—‡์„ ์˜๋ฏธํ•˜๋Š”์ง€ ์ดํ•ดํ•˜๊ณ  ์žˆ์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.
    • ํŒŒ์ผ ์ฝ๊ธฐ์˜ ๊ฒฐ๊ณผ๊ฐ€ ๋ฌธ์ž์—ด์ด๋ฏ€๋กœ, JSON.parse๋ฅผ ์‚ฌ์šฉํ•ด์•ผ ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

PromiseConstructor.js

const fs = require("fs");

const getDataFromFilePromise = filePath => {
  // return new Promise()
  // TODO: Promise ๋ฐ fs.readFile์„ ์ด์šฉํ•ด ์ž‘์„ฑํ•ฉ๋‹ˆ๋‹ค.
  return new Promise((resolve, reject) => {
    fs.readFile(filePath, 'utf-8', (err, data) => {
      if (err) {
        reject(err);
      } else {
        resolve(data);
      }
    });
  });
};

getDataFromFilePromise('README.md').then(data => console.log(data));

module.exports = {
  getDataFromFilePromise
};

 

BasicChaining.js

const path = require('path');
const { getDataFromFilePromise } = require('./02_promiseConstructor');

const user1Path = path.join(__dirname, 'files/user1.json');
const user2Path = path.join(__dirname, 'files/user2.json');

// HINT: getDataFromFilePromise(user1Path) ๋ฐ getDataFromFilePromise(user2Path)๋ฅผ ์ด์šฉํ•ด ์ž‘์„ฑํ•ฉ๋‹ˆ๋‹ค
const readAllUsersChaining = () => {
  // TODO: ์—ฌ๋Ÿฌ๊ฐœ์˜ Promise๋ฅผ then์œผ๋กœ ์—ฐ๊ฒฐํ•˜์—ฌ ์ž‘์„ฑํ•ฉ๋‹ˆ๋‹ค
  
  // user1path ์™€ user2path ๊ฐ€ ๋ชจ๋‘ ๋‹ด๊ธด ์–ด๋–ค ๋ฐฐ์—ด์„ ๋งŒ๋“ค๊ณ  ์‹ถ์€๋ฐ
  // then ์‚ฌ์šฉํ•ด๊ฐ€์ง€๊ณ  ๋งŒ๋“ ๋‹ค.
  // ๊ทผ๋ฐ fs ์ง์ ‘ ์‚ฌ์šฉํ•˜์ง€๋ง๊ณ . ์œ„์— getdata~ import ํ•œ ๊ฑฐ ์‚ฌ์šฉํ•ด์„œ ๋งŒ๋“ค์–ด์ค˜๋ผ.

  let result = []; // userpath ๋‹ด์•„์ค„ ๊ทธ๋ฆ‡ ๋งŒ๋“ค๊ธฐ
  return getDataFromFilePromise(user1Path)
  .then((value)=>{
    let parse1 = JSON.parse(value);
    result.push(parse1);
    return getDataFromFilePromise(user2Path)
  })
  .then((value)=>{
    let parse2 = JSON.parse(value);
    result.push(parse2);

    return result;
  })
}

readAllUsersChaining();

module.exports = {
  readAllUsersChaining
}
728x90
๋”๋ณด๊ธฐ
Document/๋จ•์„ ์ƒ์˜ ์ฝ”๋”ฉ๊ต์‹ค