sprint - async & promise

FeelSoo·2022년 4월 23일
0


링크텍스트 --- promise.all 사용법

링크텍스트 -- dirname 사용법




part 2의 목표는 브라우저 환경의 데이터를 가져오는 것이 아닌 로컬 파일의 데이터를 불러와 작업을 진행하는 것이다.




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
}




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







part 3는 Node.js 환경을 벗어나 ( 백엔드 단을 벗어나 ) fech API로 HTTP 요청과 응답을 받는 연습을 합니다. ( 프론트 엔드단 )




part 3 - (1) basicChaning.js

var newsURL = 'http://localhost:4999/data/latestNews';
var weatherURL = 'http://localhost:4999/data/weather';

function getNewsAndWeather() {
  // TODO: fetch을 이용해 작성합니다
  // TODO: 여러개의 Promise를 then으로 연결하여 작성합니다

  let result = {};

  return fetch(newsURL)       // fetch는 특정 URL로부터 정보를 받아온다
    .then(newsdata => newsdata.json())    // fetch API는 json()메서드가 내장되있음. 받아온 인자 newsdata를 JSON 형태로 변환 후 promise로 전달
    .then((json) => {             // 위의 값을 받아온 인자를 json이라고 칭한다
      result.news = json.data     // 빈 배열 result에 news 속성으로 담아준다
      return fetch(weatherURL)
    })
    .then(weatherdata => weatherdata.json())
    .then((json) => { 
        result.weather = json       //위의 내용 반복
        return result;              // result 리턴
    })
}

if (typeof window === 'undefined') {
  module.exports = {
    getNewsAndWeather
  }
}






part 3 - (1) promiseAll.js

var newsURL = 'http://localhost:4999/data/latestNews';
var weatherURL = 'http://localhost:4999/data/weather';

function getNewsAndWeatherAll() {
  // TODO: Promise.all을 이용해 작성합니다
  let result = {};    // 빈 객체 선언
  const news = fetch(newsURL).then(newsdata => newsdata.json()) // newsURL로부터 데이터를 받아온 후 json화시키고 await을 걸어준다
  const weather = fetch(weatherURL).then(weatherdata => weatherdata.json())

  return Promise.all([news, weather])   //news, weather로부터 데이터를 가져온 후 판별
    .then(([newsResponse, weatherResponse]) => {  //true면 newsResponse, weatherResponse에 관한 식을 선언
      result.news = newsResponse.data     // result에 news 속성으로 newsResponse의 data 속성값을 넣어준다
      result.weather = weatherResponse     // result에 weather 속성으로 weatherResponse의 data 속성값을 넣어준다
      return result;                      // result 반환
    })
}

if (typeof window === 'undefined') {
  module.exports = {
    getNewsAndWeatherAll
  }
}






part 3 - (1) asyncAwait.js

var newsURL = 'http://localhost:4999/data/latestNews';
var weatherURL = 'http://localhost:4999/data/weather';

async function getNewsAndWeatherAsync() {
  // TODO: async/await 키워드를 이용해 작성합니다
  let result = {};
  const news = await fetch(newsURL).then(newsdata => newsdata.json()) // newsURL로부터 데이터를 받아온 후 json화시키고 await을 걸어준다
  const weather = await fetch(weatherURL).then(weatherdata => weatherdata.json()) 

  return Promise.all([news, weather])     //  //news, weather로부터 데이터를 가져온 후 판별
    .then(([newsResponse, weatherResponse]) => { //true면 newsResponse, weatherResponse에 관한 식을 선언
      result.news = newsResponse.data   // result에 news 속성으로 newsResponse의 data 속성값을 넣어준다
      result.weather = weatherResponse  // // result에 weather 속성으로 newsResponse의 data 속성값을 넣어준다
      return result;                  // result 반환
    })
}

if (typeof window === 'undefined') {
  module.exports = {
    getNewsAndWeatherAsync
  }
}






profile
세상은 넓고 배울건 많다

0개의 댓글