JS/Node 비동기 호출 2

요니·2022년 10월 6일
0
post-thumbnail

👩‍💻 배운것

fs.readFile을 이용한 callback, Promise 구현하기

  1. callBack.js
const fs = require("fs");

const getDataFromFile = function (filePath, callback) {
  // TODO: fs.readFile을 이용해 작성합니다
  fs.readFile(filePath, 'utf-8', (err, data)=>{
    if (err){
      callback(err,null);
    } else{
      callback(null, data);
    }
  })
};

getDataFromFile('README.md', (err, data) => console.log(data));

module.exports = {
  getDataFromFile
};
  1. promiseConstructor.js
const {readFile} = require("fs");

const getDataFromFilePromise = filePath => {
  // TODO: Promise 및 fs.readFile을 이용해 작성합니다.
  return new Promise((resolve, reject)=>{
    readFile(filePath, 'utf-8', (err,data)=>{
      if(err){
        reject(err)
      } else{
        resolve(data);
      }
    })
  })
};

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

module.exports = {
  getDataFromFilePromise
};
  1. basicChaining.js
const { get } = require('http');
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으로 연결하여 작성합니다
  let result=[];
  return getDataFromFilePromise(user1Path)
  .then((value)=>{
    let parsed1 = JSON.parse(value)
    result.push(parsed1)
    return getDataFromFilePromise(user2Path)
  })
  .then((value)=>{
    let parsed2 = JSON.parse(value)
    result.push(parsed2)
    return result
  })
}

readAllUsersChaining();

module.exports = {
  readAllUsersChaining
}
  1. promiseAll.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');

const readAllUsers = () => {
  // TODO: Promise.all을 이용해 작성합니다
  const user1 = getDataFromFilePromise(user1Path)
  const user2 = getDataFromFilePromise(user2Path)

  return Promise.all([user1,user2])
  .then((value)=>{
    return value.map((el)=>JSON.parse(el))
  })
}

readAllUsers()

module.exports = {
  readAllUsers
}
  1. asyncAwait.js
const { parse } = require('path');
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');

const readAllUsersAsyncAwait = async() => {
  // TODO: async/await 키워드를 이용해 작성합니다
  const user1 = await getDataFromFilePromise(user1Path)
  const user2 = await getDataFromFilePromise(user2Path)

  return JSON.parse(`[${user1},${user2}]`)
} 

readAllUsersAsyncAwait();

module.exports = {
  readAllUsersAsyncAwait
}
profile
개발자가 될래요

1개의 댓글

comment-user-thumbnail
2022년 10월 6일

HA 딱 보면 답 나오길!
HAHAAT!

답글 달기