Async & Promise Sprint

소금·2021년 9월 10일
0
post-thumbnail

Part 2


01 callBack.js

const fs = require("fs") // fileSystem 모듈 불러오기

const getDataFromFile = function(filePath, callback) { //경로와 콜백함수가 인자
  fs.readFile(filePath, 'utf8', (err, data) => { // 파일의 내용을 불러와서
    if(err)return callback(err,null); // 에러가 있다면 콜백함수에 err을 넣어 호출
    else return callback(null,data); // 그 외에는 데이터를 콜백함수에 넣어 호출
  }
}

//함수 호출
getDataFromFile('README.md', (err,data) => console.log(data));

02 promiseConstructor.js

const fs = require("fs") // fileSystem 모듈 불러오기
  return new Promise((resolve, reject) => { 
  // 비동기 작업이 끝나면 호출할 resolve 함수와 오류 발생시 호출할 reject 함수
    fs.readFile(filePath, 'utf-8', (err, data) => {
    //파일의 내용을 불러오고
      if(err)return reject(err); // err가 있다면 reject 함수에 err 넣어 리턴
      else return resolve(data); // 그 외는 resolve 함수에 data 넣어 리턴
    })
  })
};

03 basicChaining.js

const user1Path = path.join(__dirname, 'files/user1.json');
const user2Path = path.join(__dirname, 'files/user2.json');
//path.join() 인자로 받은 경로들을 하나로 합쳐서 문자열 형태로 path를 리턴한다.
//console.log(__dirname) === file 명을 제외한 절대 경로 
 ex)  /Users/salt/temp

const readAllUsersChaining = () => {
  return getDataFromFilePromise(user1Path) //02번의 프로미스를 받고
    .then((user1) => { //user1의 데이터를 인자로 받아서 
      return getDataFromFilePromise(user2Path).then((user2) => {
      //user2의 데이터도 인자로 받아서
        return '[' + user1 + ',' + user2 + ']';
        //user1과 user2의 데이터를 받아서 활용함
      });
    })
    .then((text) => JSON.parse(text)); // 위의 데이터를 파싱해줌 
};

readAllUsersChaining(); 함수 실제 호출

04 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 = () => {
  return Promise.all([
  //Promise.all은 각 promise의 결과를 배열 형태로 리턴해줌
    getDataFromFilePromise(user1Path),
    getDataFromFilePromise(user2Path),
  ])
    .then(([user1, user2]) => { //구조분해 할당
      return '[' + user1 + ',' + user2 + ']';
    })
    .then((text) => JSON.parse(text));
};

// readAllUsers()

05 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 () => { // async 함수 호출
  let user1 = await getDataFromFilePromise(user1Path); 
  //기다려서 받아온 데이터를 변수에 할당 
  let user2 = await getDataFromFilePromise(user2Path);

  let text = '[' + user1 + ',' + user2 + ']';
  let json = JSON.parse(text);
  return json;
};

// readAllUsersAsyncAwait();

Part 3


01 basicChaining.js

function getNewsAndWeather() {
  const newsURL = 'http://localhost:5000/data/latestNews'; 
  const weatherURL = 'http://localhost:5000/data/weather';
  //받아올 하드코딩 데이터의 주소를 변수에 할당

  return fetch(newsURL) // newsURl에 요청을 보내 데이터를 받아오고,
    .then((resp) => resp.json()) //해당 데이터를 json화 시켜줌
    .then((json1) => { //그 이후에
      return fetch(weatherURL) // weatherURL에 요청을 보내 데이터를 받아옴
        .then((resp) => resp.json()) 
        .then((json2) => {
          return { // 위에서 받아와 json화 시켜준 데이터를 가지고 
            news: json1.data, // 객체에 넣어줌 !
            weather: json2,
          };
        });
    });
}

02 promiseAll.js

  
function getNewsAndWeatherAll() {
  const newsURL = 'http://localhost:5000/data/latestNews';
  const weatherURL = 'http://localhost:5000/data/weather';

  return Promise.all([fetch(newsURL), fetch(weatherURL)])
  //Promise.all을 통해 각 데이터의 주소에서 응답을 받아 배열 형태로 리턴
    .then(([newsResponse, weatherResponse]) => { //구조분해 할당
      return Promise.all([newsResponse.json(), weatherResponse.json()]); // json화
    })
    .then(([json1, json2]) => {
      return { // 데이터를 객체에 넣어줌
        news: json1.data,
        weather: json2,
      };
    });
}

03 asyncAwait.js

async function getNewsAndWeatherAsync() {
  const newsURL = 'http://localhost:5000/data/latestNews';
  const weatherURL = 'http://localhost:5000/data/weather';

  const json1 = await fetch(newsURL).then((resp) => resp.json());
  const json2 = await fetch(weatherURL).then((resp) => resp.json());

  return {
    news: json1.data,
    weather: json2,
  };
}
profile
Salty as Salt

0개의 댓글