카테고리 없음
타이머 API(feat. 비동기 부들부들)
novem
2023. 1. 19. 21:09
part 2-1)
fs.readFile(filePath, "utf-8", (err, data) => {
if(err) callback(err, null);
else {
callback(null, data)
}
})
};
// fs.readFile 메소드를 사용해 파일의 내용을 읽기
// 첫번째 인자는 읽어들일 파일의 경로, 두번째 인자는 인코딩 타입, 세번째 인자는 콜백 함수
// 콜백 함수는 에러와 파일의 데이터를 인자로 받아 처리
// 이 콜백 함수에서 에러가 발생하면 err 객체를 인자로 callback 함수를 실행
// 정상적으로 읽어들인 경우에는 data를 인자로 callback 함수를 실행
2-2)
return new Promise(function(resolve, reject) {
fs.readFile(filePath,'utf-8',(err,data)=>{
if(data) resolve(data);
else reject(err);
});
});
};
// fs 모듈을 사용하여 filePath로 지정된 파일을 'utf-8'로 읽은 파일 내용은 data변수에 저장
// 읽은 데이터가 있다면(data), resolve(data)를 호출하여 파일 내용을 반환
// 그렇지 않으면(err), reject(err)를 호출하여 에러를 반환
2-3)
const promise = getDataFromFilePromise(user1Path)
.then(function (user){ //than에서 반환하는 값은 자동적으로 promise가 된다 -> than에서 받는 값은 프로미스 객체임
users.push(JSON.parse(user)); //promise를 받아서 user를 읽어서 넣고
return getDataFromFilePromise(user2Path); //다시 user2를 읽는 promise를 리턴을 해서
})
.then(function (user){
users.push(JSON.parse(user)); //user2를 받아서 또 user2를 넣고
return users; //user배열을 promise로 리턴을 해서
});
return promise; // 그 promise를 다시 리턴을 한다.
};
2-4)
return Promise.all([
getDataFromFilePromise(user1Path),
getDataFromFilePromise(user2Path),
])
.then (([user1, user2]) => {
return `[${user1}, ${user2}]` // [${user1}, ${user2}] 형식의 문자열 반환
})
.then((text)=>JSON.parse(text)); // 이를 json 객체로 변환
}
// Promise.all() 메소드를 사용하여 getDataFromFilePromise 함수를 호출
// user1Path와 user2Path로 지정된 파일을 읽는 두 개의 Promise 객체를 배열로 묶음
// .then() 메소드를 사용하여 읽은 파일 데이터를 처리
// 읽은 데이터를 [user1, user2] 형식으로 감싸는 문자열을 만들기
// JSON.parse()로 파싱 하여 객체로 변환
// 동시에 두개의 파일을 읽은 후 파싱
2-5)
const readAllUsersAsyncAwait = async () => {
const arr=[];
const res = await getDataFromFilePromise(user1Path);
arr.push(JSON.parse(res));
const res2 = await getDataFromFilePromise(user2Path);
arr.push(JSON.parse(res2)); //await은 promise에서 then으로 받아온 값을 리턴
return arr;
}
// const readAllUsersAsyncAwait = async () => { 로 시작하여 함수를 async로 선언하여 비동기 함수를 생성
// user1Path와 user2Path로 지정된 파일을 읽는데 await 키워드를 사용하여 파일을 읽는 것을 동기적으로 처리
// 반환되는 값은 JSON.parse()를 사용하여 객체로 변환하고, arr 배열에 push
// arr를 반환
// async/await 기능을 사용하여 동기적으로 두개의 파일을 읽은 후 파싱
part 3-1)
//객체로 반환해야한다.(빈객체만들고 거기에 넣기)
let result = {};
return fetch(newsURL)
.then(response => response.json())
.then((newsData) => {
//result.news newsData.data데이서의 형태 객체안에 배열이 있기때문에 data안에 값을 넣어줘야함. 데이터를 보면서 이해하기.
result.news = newsData.data
//순차적으로 실행하기위해서
return fetch(weatherURL)
.then(response => response.json())
.then((newsData2) => {
//newsData2는 객체 그 자체여서 newsData.data처럼 안됨.
result.weather = newsData2;
return result
})
})
3-2)
const getNews = fetch(newsURL)
.then((response) => response.json())
.then((json) => json)
.catch((error) => error);
const getWeather = fetch(weatherURL)
.then((response) => response.json())
.then((json) => json)
.catch((error) => error);
return Promise.all([getNews, getWeather]) // Promise.all 은 배열을 인자로 받는다.
.then((data) => {
let result = {};
result['news'] = data[0]['data'];
result['weather'] = data[1];
return result;
})
.catch((err) => err);
}
// getNews와 getWeather에서 각각 newsURL과 weatherURL로 지정된 API를 호출하여 데이터를 가져와랏
// Promise.all([getNews, getWeather])를 호출하여 getNews와 getWeather를 동시에 실행해랏
// .then()를 사용하여 데이터를 처리
// data라는 변수에 각각의 데이터를 담아서 result 객체에 news와 weather 속성으로 각각의 데이터를 저장
// .catch()를 사용하여 에러를 처리
3-3)
let result = {} // 결과를 저장할 객체를 선언
let news = await fetch(newsURL).then(res => res.json())
// fetch(newsURL)를 호출하여 newsURL로 지정된 API를 호출
// response를 json으로 파싱한 결과를 news라는 변수에 할당
let weather = await fetch(weatherURL).then(res => res.json())
// fetch(weatherURL)를 호출하여 weatherURL로 지정된 API를 호출
// response를 json으로 파싱한 결과를 weather라는 변수에 할당
result.news = news.data
// news 객체의 data 속성을 result 객체의 news 속성에 할당
result.weather = weather
// weather 객체를 result 객체의 weather 속성에 할당
return result