在这个应用程序中,我想维护一个日志文件。执行时可能会抛出一些异常。如果有异常,我也想记录它。但实际发生的是在将消息记录到日志文件之前终止应用程序。我尝试仅对log()
方法使用promise,它没有修复订单。我该如何解决这个问题?如果我使用promises,我是否必须在每种方法中使用promises(或在每种方法中返回新的promise)?或者还有其他更好的解决方案吗? createWriteStream.write()
是asynchronous
函数吗?如果这是为什么它有回电?
//this is my object
var fileHandler = function () {};
//this log everything into a log file
fileHandler.prototype.log = function (logContent) {
var logWriter = FS.createWriteStream(logFilePath, {
flags: 'w',
defaultEncoding: 'utf8',
autoClose: true
});
console.log(logContent);
logWriter.write(logContent+'\n');
/*
promise.resolve()
.then(function () {
var logWriter = FS.createWriteStream(logFilePath, {
flags: 'w',
defaultEncoding: 'utf8',
autoClose: true
});
console.log(logContent);
})
.then(function () {
logWriter.write(logContent+'\n');
})
*/
};
//Expedted result:
//if "isTrue" == false,
//01.this.log() should write the message to file
//02.after that print "test" in console
//03.and then terminate the application with an exception
//But the actual result:
//when i debug
//logWriter.write(logContent+'\n'); is executed
//but doesn't log the message before an exceptions is thrown.
fileHandler.prototype.createItem = function (isTrue) {
if(isTrue){
this.log('it\'s true');
}
else{
this.log('newException : it\'s not true');
throw new this.setUserException('newException', 'it\'s not true');
}
};
//create new instance
var projectModule = new fileHandler();
//add cteate method to projectModule object
projectModule.create = function (isTrue) {
this.createItem(isTrue);
};
//call create function
projectModule.create(false);