TIL 👩🏻‍💻

TIL : Promise & Async (2)

heesue 2021. 4. 27. 23:49

이번에는 Promise와 Async에 대한 개념을 바탕으로 스프린트를 진행했다.


1. fs module : fs.readFile 메서드는 비동기적으로 파일 내용 전체를 읽는다.

fs.readFile(path[, options], callback)

· path : <string> | <Buffer> | <URL> | <integer> (주로 문자열)
· options : <Object> | <string> (문자열로 전달할 경우 주로 'utf8'이라는 인코딩 방식으로 연다.)

· callback : <Function> (err : <Error>, data : <string> | <Buffer>)

 

- callback

const fs = require("fs");

const getDataFromFile = function (filePath, callback) {
  fs.readFile(filePath, "utf8", function (err, file) {
    if (err) {
      callback(err, null);
    } else {
      callback(null, file.toString());
    }
  });
};

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

module.exports = {
  getDataFromFile
};

 

- promise constructor : callback 파라미터 대신 promise의 resolve, reject 이용

const fs = require("fs");

const getDataFromFilePromise = filePath => {
  return new Promise((resolve, reject) => {
    fs.readFile(filePath, "utf8", function (err, file) {
      if (err) {
        reject(err);
      } else {
        resolve(file.toString());
      }
    });
  });
};

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

module.exports = {
  getDataFromFilePromise
};

 

- basic chaining : 두 파일을 합쳐서 두 객체가 담긴 배열 만들기

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');

// getDataFromFilePromise(user1Path)와 getDataFromFilePromise(user2Path)를 이용해 작성
const readAllUsersChaining = () => {
  let arr = [];
  return getDataFromFilePromise(user1Path)
  .then((user1) => {
    arr.push(JSON.parse(user1));
    return getDataFromFilePromise(user2Path)
    
    .then((user2) => {
      arr.push(JSON.parse(user2));
      return arr;
    });
  });
}

// readAllUsersChaining();

module.exports = {
  readAllUsersChaining,
};

 

- Promise.all

인자로 iterable한 객체가 들어온다.

const { get } = require('http');
const path = require('path');
const { values } = require('underscore');
const { getDataFromFilePromise } = require('./02_promiseConstructor');

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

const readAllUsers = () => {
  const user1 = getDataFromFilePromise(user1Path).then((data) => JSON.parse(data));
  const user2 = getDataFromFilePromise(user2Path).then((data) => JSON.parse(data));

  return Promise.all([user1, user2])
  .then((data) => data);
}

// readAllUsers()

module.exports = {
  readAllUsers
}

 

- async / await

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() => {
  const user1 = await getDataFromFilePromise(user1Path);
  const user2 = await getDataFromFilePromise(user2Path);

  return [JSON.parse(user1), JSON.parse(user2)];
}

// readAllUsersAsyncAwait();

module.exports = {
  readAllUsersAsyncAwait
}

 


2. fetch API

서버를 먼저 실행하고 fetch를 통해 데이터를 보내고 받아오도록 실행한다.

(callback 형태의 요청이 존재하지 않으므로 chaining, Promise.all, async / await을 이용한다.)

 

- basic chaining

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

function getNewsAndWeather() {
  let obj = {};
  return fetch(newsURL)
  .then((response) => response.json())
  .then((json1) => {
    obj.news = json1.data;
    return fetch(weatherURL)
  })
  .then((response) => response.json())
  .then((json2) => {
    obj.weather = json2;
    return obj;
  });
}

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

 

- Promise.all

const { json } = require("express");
const { result } = require("underscore");

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

function getNewsAndWeatherAll() {
  let obj = {};

  return Promise.all([fetch(newsURL), fetch(weatherURL)])
  .then(([news, weather]) => {
    return Promise.all([news.json(), weather.json()])
  })
  .then(([json1, json2]) => {
    obj.news = json1.data;
    obj.weather = json2;
    return obj;
  })
}

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

 

- async / await

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

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

  return {
    news: json1.data,
    weather: json2,
  };
}

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

'TIL 👩🏻‍💻' 카테고리의 다른 글

TIL : Chatterbox Client  (0) 2021.04.29
TIL : HTTP  (0) 2021.04.28
TIL : Promise & Async (1)  (0) 2021.04.27
TIL : Algorithm (2)  (0) 2021.04.20
TIL : Algorithm (1)  (0) 2021.04.19