DevLog
TIL(20210728) - 비동기(callback, promise, promiseAll, asyncAwait) + fs모듈, fetch() 본문
🤔 TIL(Today I Learned)
TIL(20210728) - 비동기(callback, promise, promiseAll, asyncAwait) + fs모듈, fetch()
Seungjae Lee 2021. 7. 28. 22:45🎁 Today
- callback, promise, promiseAll, asyncAwait 와 fs모듈을 이용해서 코드짜기
- fetch를 이용하여 api 요청하기
- 리턴값과 파라미터 값이 동일하면 생략 가능
🤔 Learned
callback
const fs = require("fs");
const getDataFromFile = function (filePath, callback) {
fs.readFile(filePath, 'utf-8', (err, data) => {
if (err) {
callback(err, null)
} else {
callback(null, data)
}
});
};
getDataFromFile('README.md', (err, data) => console.log(data));
promise
const fs = require("fs");
const getDataFromFilePromise = filePath => {
return new Promise((resolve, reject) => {
fs.readFile(filePath, 'utf-8', (err, data) => {
if (err) {
reject(err);
} else {
resolve(data)
}
});
})
};
getDataFromFilePromise('README.md').then(data => console.log(data));
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');
// HINT: getDataFromFilePromise(user1Path) 맟 getDataFromFilePromise(user2Path) 를 이용해 작성합니다
const readAllUsersChaining = () => {
// TODO: 여러개의 Promise를 then으로 연결하여 작성합니다
const result = [];
return getDataFromFilePromise(user1Path)
.then(result1 => {
return getDataFromFilePromise(user2Path)
.then(result2 => {
return [result1, result2].map(el => JSON.parse(el));
})
})
}
readAllUsersChaining();
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 = () => {
const result = [];
return Promise.all([
getDataFromFilePromise(user1Path),
getDataFromFilePromise(user2Path)
])
.then(data => data.map(data => JSON.parse(data)));
}
readAllUsers()
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');
async function readAllUsersAsyncAwait() {
const result = [];
await getDataFromFilePromise(user1Path)
.then(JSON.parse)
.then(data1 => result.push(data1))
await getDataFromFilePromise(user2Path)
.then(JSON.parse)
.then(data2 => result.push(data2))
return result;
}
readAllUsersAsyncAwait();
fetch를 이용하여 api 호출
basic chaining
var newsURL = 'http://localhost:5000/data/latestNews';
var weatherURL = 'http://localhost:5000/data/weather';
function getNewsAndWeather() {
const obj = {};
return fetch(newsURL)
.then(response => response.json())
.then(json => {
obj.news = json.data;
return fetch(weatherURL);
})
.then(response => response.json())
.then(json => {
obj.weather = json;
return obj;
})
}
promiseAll
var newsURL = 'http://localhost:5000/data/latestNews';
var weatherURL = 'http://localhost:5000/data/weather';
function getNewsAndWeatherAll() {
// TODO: Promise.all을 이용해 작성합니다
const obj = {};
return Promise.all([
fetch(newsURL).then(response => response.json()),
fetch(weatherURL).then(response => response.json())
])
.then(jsonArray => {
obj.news = jsonArray[0].data;
obj.weather = jsonArray[1];
return obj;
})
// //reference
// return Promise.all([fetch(newsURL), fetch(weatherURL)])
// .then(([newsResponse, weatherResponse]) => {
// return Promise.all([newsResponse.json(), weatherResponse.json()]);
// })
// .then(([json1, json2]) => {
// return {
// news: json1.data,
// weather: json2,
// };
// });
}
asyncAwait
var newsURL = 'http://localhost:5000/data/latestNews';
var weatherURL = 'http://localhost:5000/data/weather';
async function getNewsAndWeatherAsync() {
// TODO: async/await 키워드를 이용해 작성합니다
const obj = {};
await fetch(newsURL)
.then(response => response.json())
.then(json => obj.news = json.data)
await fetch(weatherURL)
.then(response => response.json())
.then(json => obj.weather = json)
return obj;
}
if (typeof window === 'undefined') {
module.exports = {
getNewsAndWeatherAsync
}
}
🌈 Tomorrow
- 클라이언트 서버, 브라우저, 통신 학습
- 자료구조
- Node.js 학습
'🤔 TIL(Today I Learned)' 카테고리의 다른 글
Node Sever만들기 (0) | 2021.09.08 |
---|---|
TIL(20210729) - HTTP/ 네트워크 (0) | 2021.07.29 |
TIL(20210727) - 비동기(callback, promise, asyncAwait) (0) | 2021.07.27 |
TIL(20210723) - BFS & DFS (0) | 2021.07.23 |
TIL(20210722) - 자료구조(Stack, Queue, Tree, Graph) (0) | 2021.07.22 |
Comments