코드스테이츠 42기/[TIL] Section 2

S2U3 [Js/Node] 비동기 2

랜덤다이스 2022. 11. 23. 18:12

 

part 2 - (1) callBack.js

const fs = require("fs");  /// file system이라는 모듈을 require 메서드로 가져온 후 fs로 정의

const getDataFromFile = function (filePath, callback) { // getDataFromfile --- 이 함수는 파일로부터 데이터를 불러온다. filePath와 callback함수를 인자로 가짐
  // TODO: fs.readFile을 이용해 작성합니다


  /// fs(file system)에서 readfile(method) 하는 함수를 정의. fs.readFile은 3가지 인자를 받음
  //  fs.readFile(path, [option], callback)
  
  //utf8이라는 형식의 엔코딩으로 (생략 가능) filepath를/ 그리고 callback 함수와 함께 정의하겠다 fs.readfile함수를
  //그런데 그 callback 함수는 (err, data)를 인자로 갖는 함수

  fs.readFile(filePath, 'utf8', (err, data) => { 
    if(!err) {
      callback(null, data) /// 에러가 발생하지 않았으면 앞 인자에 null을 넣어준다
    }
    else if(err) {
      callback(err, null) /// 에러가 발생했으면 앞 인자에 에러를 넣어준다
    }
  })                                
};

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

/// 'README.md' & callback func(err, data) 인자로 갖고 data를 console.log 하는 함수 getDataFromFile를 콜백

module.exports = {
  getDataFromFile
};






part 2 - (2) promiseConstructor.js

const fs = require("fs");

const getDataFromFilePromise = filePath => {
  // return new Promise()
  // TODO: Promise 및 fs.readFile을 이용해 작성합니다.

  return new Promise((resolve, reject) => {
    fs.readFile(filePath, 'utf8', (err,data) => {
    if(!err) {                /// 에러가 아니면
      resolve(data)           /// callback 함수인 resolve에 data를 담아놓는다
    }
    else if(err) {            //에러면
      reject(err)             /// callback 함수인 reject에 err를 담아놓는다
    }
    })
  })
};

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

module.exports = {
  getDataFromFilePromise
};






part 2 - (3) basicChaning.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으로 연결하여 작성합니다

  let arr = []
  return getDataFromFilePromise(user1Path)
  .then((data1) => {
    return getDataFromFilePromise(user2Path)
    .then((data2) => { 
      arr.push(JSON.parse(data1),JSON.parse(data2)) /// 객체인 data1, data2를 JSON.parse를 이용해 추출하여 arr에 푸쉬
      return arr
    })
  })
}

// readAllUsersChaining();

module.exports = {
  readAllUsersChaining
}






part 2 - (4) 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을 이용해 작성합니다
  return Promise.all([ getDataFromFilePromise(user1Path), getDataFromFilePromise(user2Path) ]) 
  //user1Path, user2Path를 통해 데이터를 가져온 뒤 
  .then(([user1, user2]) =>{
  // JSON화 시킨 user1, user2 네임을 반환한다
    return JSON.parse(`[${user1},${user2}]`)
  })
}

// readAllUsers()

module.exports = {
  readAllUsers
}






part 2 - (5) asyncAwait.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 readAllUsersAsyncAwait = async () => {
  // TODO: async/await 키워드를 이용해 작성합니다. await 연산자는 async function 내부에서만 사용 가능합니다
  //await 문은 Promise가 fulfill되거나 reject 될 때까지 async 함수의 실행을 일시 정지하고, Promise가 fulfill되면 async 함수를 일시 정지한 부분부터 실행합니다. 
  //이때  await 문의 반환값은 Promise 에서 fulfill된 값이 됩니다.

  //만약 Promise가 reject되면, await 문은 reject된 값을 throw합니다.

  const data1 = await getDataFromFilePromise(user1Path)     // data1은 user1Path의 데이터를 가져오고 promise 판별이 날 때까지 async 함수의 실행을 일시 정지할 수 있다.
  const data2 = await getDataFromFilePromise(user2Path)     // data2은 user1Path의 데이터를 가져오고 promise 판별이 날 때까지 async 함수의 실행을 일시 정지할 수 있다.

  return JSON.parse(`[${data1},${data2}]`)    // data1, data2를 JSON 형턔로 반환한다
}

// readAllUsersAsyncAwait();

module.exports = {
  readAllUsersAsyncAwait
}

참조 : https://velog.io/@chlvlftn22/sprint-async-promise


part2의 (2)까지는 fs 모듈을 활용해 파일을 불러왔다면 (3)부터는 path.join(__dirname, ~ ) 을 활용하여 파일을 불러온다.

작은 프로젝트라도 실제로 구현 해보는게 중요

큰 프로젝트는 작은 기능들이 모여서 이루어진다

레퍼런스를 맍이 살펴보는것 만으로도 시야가 넓어진다

아는 코드는 다음에 검색 할 필요가 없다

나의 블로그는 면접관의 질문지

면접준비중 도움받은 책 : 모던자바스크립트 Deep Dive

무작정 많이 지원해라 할지 말지는 나중에 선택

면접은 공짜 학습 듀토리얼이다

완성된 개발자란 없다

포트폴리오시 구현하면 좋은것

함께 만들어가는 경험이 추후 협업에 중요하다

면접질문답변 모음

이런건 해봤으면 한다

  • 내가 어떤개발자인지 보여줄 수 있는 매체를 만들어 관리하기
  • 다른 개발자들 코드와 글 훔쳐보기
  • 간단하 코드 많이 써보기
  • 협업 툴 다뤄보기

이것만은 하지 말았으면 한다

  • 혼자 개발하기
  • 개발할 준비만하기
  • 조급한 마음 갖기