프로그래밍/의문
node.js에서 파일 등을 읽어서 객체를 생성할 때
제페
2017. 7. 26. 10:13
반응형
객체가 생성되는데, 파일을 읽어서 초기화 시키고 싶었다. 왜냐면 깔끔하게 보이니까.
const object = new AnyObject("config.json");
근데 AnyObject 생성자에 readFile등의 비동기 동작이 있었다면 어떨까
class AnyObject{
constructor(fileName){
fs.readFile(...);
}
}
물론 fs엔 readFileSync가 있다지만 그건 이 상황에 대한 근본적인 해결이 아니다. 만약 sync 함수가 지원되지 않는다면 어쩔건데?
그에 여기에 대한 좋은 의견이 있다.
Is it bad practice to have a constructor function return a Promise?
Ask yourself: Do you actually need the instance without the data? Could you use it somehow?
결론적으로 일단 데이터는 외부에서 읽고, 읽은 데이터를 바탕으로 AnyObject를 초기화 시키는 것이 가장 좋다는 것이다.
const fs = require("fs");
class Object
{
constructor(name, hp){
this.name = name;
this.hp = hp;
}
print(){
console.log(`name: ${this.name} hp: ${this.hp}`);
}
static createObjectFromFile(fileName){
return new Promise((resolve, reject)=>{
fs.readFile(fileName, (err, data)=>{
if(err){
reject(err);
}
else{
var newObject = new Object("boo", 100);
resolve(newObject);
}
});
});
}
}
// 안 좋은 케이스!
//const object = new Object("config.xml");
// 좋은 케이스!
Object.createObjectFromFile("config.xml")
.then(obj=>obj.print())
.catch(err=>console.log(err));
반응형