async-and-promise

이동국·2022년 10월 4일
0

async-and-promise

이번 시간에는 위 영상과 같이 callback과 promise그리고 async await를 클릭했을 때 나타나는 변화를 보면서 스프린트를 진행하였다.

Promise

Promise는 비동기적으로 실행하는 작업의 결과를 나타내는 객체이다.
가장 중요한 특징이자 장점으로 비동기의 결과를 객체화 시킨다는 점이다.
이번 과제는 타이머 API를 이용하여 비동기를 구현해 보았다.

1. callBack

콜백 함수를 통한 비동기 처리

const fs = require("fs");  // 파일 시스템 모듈을 불러옵니다
const dns = require('dns'); // DNS 모듈을 불러옵니다


const getDataFromFile = function (filePath, callback) {
  
  fs.readFile(filePath, 'utf8', (err, data) => {
    if (data === undefined) {
      callback(err,null); 
    }else{
      callback(null,data);
    }
    
  });
  
};

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

module.exports = {
  getDataFromFile
};

2. promiseConstructor

const fs = require("fs");

const getDataFromFilePromise = filePath => {
  return new Promise((resolve,reject) =>{
    fs.readFile(filePath,'utf8', (err, data) => {
      if(data === undefined){
        reject(err)
      }else{
        resolve(data)
      }
    });

  });
 
};

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

module.exports = {
  getDataFromFilePromise
};

3. basicChaining

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 readAllUsersChaining = () => {
  
  return getDataFromFilePromise(user1Path)
  .then((user1) => {
    return getDataFromFilePromise(user2Path)
      .then((user2) => {
        return `[${user1}, ${user2}]`
       })
    }).then(data => JSON.parse(data))
  
}

 readAllUsersChaining();

module.exports = {
  readAllUsersChaining
}

4. promiseAll

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([getDataFromFilePromise(user1Path), getDataFromFilePromise(user2Path)])
    .then(([data1, data2]) => {
      return JSON.parse(`[${data1}, ${data2}]`);
    });
}

readAllUsers()

module.exports = {
  readAllUsers
}

5. asyncAwait

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 newuser1 = await getDataFromFilePromise(user1Path);
  const newuser2 =  await getDataFromFilePromise(user2Path);
  let result = `[${newuser1}, ${newuser2}]`
  return JSON.parse(result)
  };


 readAllUsersAsyncAwait();

module.exports = {
  readAllUsersAsyncAwait
}

6. basicChaining

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

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

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

7. promiseAll

function getNewsAndWeatherAll() {
  
  return Promise.all([
    fetch(newsURL).then(response => response.json()), 
    fetch(weatherURL).then(response => response.json())
  ])
    .then((data) =>{ 
    return {news: data[0].data, weather : data[1]};
  })
}

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

8. asyncAwait

async function getNewsAndWeatherAsync() {

  let news = await fetch(newsURL).then(response => response.json())
  let weather = await fetch(weatherURL).then(response => response.json())
  return {news: news.data, weather : weather};
}
if (typeof window === 'undefined') {
  module.exports = {
    getNewsAndWeatherAsync
  }
}

0개의 댓글