👩💻 배운것
fs.readFile을 이용한 callback, Promise 구현하기
- callBack.js
const fs = require("fs");
const getDataFromFile = function (filePath, callback) {
// TODO: fs.readFile을 이용해 작성합니다
fs.readFile(filePath, 'utf-8', (err, data)=>{
if (err){
callback(err,null);
} else{
callback(null, data);
}
})
};
getDataFromFile('README.md', (err, data) => console.log(data));
module.exports = {
getDataFromFile
};
- promiseConstructor.js
const {readFile} = require("fs");
const getDataFromFilePromise = filePath => {
// TODO: Promise 및 fs.readFile을 이용해 작성합니다.
return new Promise((resolve, reject)=>{
readFile(filePath, 'utf-8', (err,data)=>{
if(err){
reject(err)
} else{
resolve(data);
}
})
})
};
getDataFromFilePromise('README.md')
.then(data => console.log(data));
module.exports = {
getDataFromFilePromise
};
- basicChaining.js
const { get } = require('http');
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 result=[];
return getDataFromFilePromise(user1Path)
.then((value)=>{
let parsed1 = JSON.parse(value)
result.push(parsed1)
return getDataFromFilePromise(user2Path)
})
.then((value)=>{
let parsed2 = JSON.parse(value)
result.push(parsed2)
return result
})
}
readAllUsersChaining();
module.exports = {
readAllUsersChaining
}
- 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을 이용해 작성합니다
const user1 = getDataFromFilePromise(user1Path)
const user2 = getDataFromFilePromise(user2Path)
return Promise.all([user1,user2])
.then((value)=>{
return value.map((el)=>JSON.parse(el))
})
}
readAllUsers()
module.exports = {
readAllUsers
}
- asyncAwait.js
const { parse } = require('path');
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 키워드를 이용해 작성합니다
const user1 = await getDataFromFilePromise(user1Path)
const user2 = await getDataFromFilePromise(user2Path)
return JSON.parse(`[${user1},${user2}]`)
}
readAllUsersAsyncAwait();
module.exports = {
readAllUsersAsyncAwait
}
HA 딱 보면 답 나오길!
HAHAAT!