
우선 비동기식 파일 읽기에서 프로미스를 사용했다고 해도 결국 비동기식이기에 결과를 기다리지 않고 그 이후의 다음 줄의 코드를 실행하기에 try catch로 잡을 수 없다.
또한 프로미스 대신 콜백 함수를 사용한다고 해도 try catch는 코드가 실행 되는지를 확인하지 코드의 결과가 나왔는지는 확인하지 않기에 우리는 다른 방식으로 오류를 확인해야 한다.
fs.readFile('data.txt', function(error, fileData) {
if(error){
...
}
console.log('File parsing done!');
console.log(fileData.toString());
});
이런 식으로 error가 있으면 error가 true가 되기에 if문으로 확인을 할 수 있다.
fs.readFile('data.txt')
.then(function(error, fileData) {
console.log('File parsing done!');
console.log(fileData.toString());
//return anotherAsyncOperation;
})
.then(function() {})
.catch(function(error) { //<-----
console.log(error);
});
위와 같이 then 뒤에 .catch를 이어붙여서 error를 매개변수로 가지는 함수를 실행하면 된다.
프로미스에만 적용되는 내용이다.
특정 상황에서 비동기 작업을 수행할 때, 동기화 방식을 사용해야 할 때가 있을 수 있다. 그리고 패키지에서 예를 들어 readFileAsync와 같은 동기화 방식을 지원하지 않을 때 밑과 같이 해결방법이 있다.
function readFile() {
let fileData;
fs.readFile('data.txt')
.then(function(error, fileData) {
console.log('File parsing done!');
console.log(fileData.toString());
//return anotherAsyncOperation;
})
.then(function() {})
.catch(function(error) {
console.log(error);
});
console.log('Hi there!');
}
//위에는 원래 비동기식 밑에는 async와 await을 이용해서 동기식으로 수정
async function readFile() {
let fileData;
try{
fileData = await fs.readFile('data.txt');
} catch(error){
console.log(error);
}
console.log('File parsing done!');
console.log(fileData.toString());
console.log('Hi there!');
}
그럴 경우 위와 같이 function 앞에 async를 적고 메소드 앞에 await을 붙이면 이제 동기화 식으로 사용기 가능하다.
그러므로 메소드는 값을 반환을 할 수 있고 동기식으로 진행되기에 then은 필요없고 그냥 밑에다가 다음 실행될 코드들을 작성하면 된다.
또한 동기식이기에 try-catch를 사용할 수도 있다.
-> 사실 이론적으로만 배우니 얘가 어디서 사용될 지 감이 오지는 않는다. 실전에서 사용을 해보는 경험이 필요할 듯.
이제 데이터베이스를 들어가기 시작했다.
행과 열을 사용하지만 쿼리가 많은 SQL과 행과 열 대신 정보를 모아둬서 정보가 중첩되지만 쿼리가 적은 noSQL 이 두 종류가 있다.
SQL은 mySQL로 noSQL은 mongoDB로 할 예정인 것 같다.
먼저 mySQL로 시작하던데, 프로그램을 다운받고 여러가지를 하더라 다행이 goormIDE에서도 mySQL을 지원한다고 하니 계속 따라 갈 수 있을 듯 하다.
물룬 좀 찾아보고 시도해봐야하긴 하다.. ㅎ 뭐 사지방의 한계겠지.
암튼 내일 구름에서 mysql 세팅하고 강의 마저 들으면 될 것 같다.
가자 데베의 세계로.