const getDataFromFile = function (filePath, callback) {
// TODO: fs.readFile을 이용해 작성합니다
fs.readFile(filePath,"utf8",function(err,data){
if(err){
callback(err , null);
}else{
callback(null , data);
}
});
};
const fs = require("fs");
const getDataFromFilePromise = filePath => {
// return new Promise()
// TODO: Promise 및 fs.readFile을 이용해 작성합니다.
return new Promise((resolve , reject)=>{
fs.readFile(filePath, "utf8", (err, data)=>{
if(err){
reject(err)
}else{
resolve(data)
}
});
}
)}
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(text => JSON.parse(text))
}
return getDataFromFilePromise(user1Path)
.then(console.log)를 찍으면 user1.json객체가 나오게 된다
then안에 임의의 인자 user1을 넣고 바로 user2path를 리턴을 해준다 이후
.then으로 배열안에 넣어 리턴을 해주는데 이때 주의점!
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(([user1, user2]) => {
return '[' + user1 + ',' + user2 + ']';
})
.then(text => JSON.parse(text))
}
.then((data)=>{
return data.map((el)=>JSON.parse(el));
})
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 키워드를 이용해 작성합니다
let a = await getDataFromFilePromise(user1Path);
let b = await getDataFromFilePromise(user2Path);
return [JSON.parse(a), JSON.parse(b)]
}
1.then이라는 매서드안에 왜 인자를 넣는가에 대하여
2.callback함수에 err,data넣는이유