在回调中设置对象属性



我很有信心,有一些与this,我做错了。这个问题以前已经问过了,但是即使在回顾了其他的问题和答案之后,我仍然不能让它工作。

基本上问题是,我不能设置file.fileType是我需要它从magic.detectFileType内的回调函数内的值。

var Magic = mmm.Magic,
    magic = new Magic(mmm.MAGIC_MIME_TYPE),
for (var i in files){
    var file = new File(files[i])
    file.detectFileType();
    commandSelf.log("File Type: " + file.fileType);
    commandSelf.log("File Name: " + file.filename);
    commandSelf.log("Full Path: " + file.fullPath);
} 
var File = function(filename){
    this.filename = filename;
    this.fullPath = null;
    this.fileType = null;
};
File.prototype.detectFileType = function(){
    this.fullPath = path + "/" + this.filename;
    var self = this;
    // Make sure this is an appropriate image file type
    magic.detectFile(this.fullPath, function(err, result){
        self.fileType = "test"
    });
}

一个更合适的解决方案是让detectFileType接受回调或返回一个承诺,以便您知道何时异步任务已经完成,并且您可以安全地检查File实例属性。例如:

var Magic = mmm.Magic;
var magic = new Magic(mmm.MAGIC_MIME_TYPE);
files.forEach(function(file) {
    file = new File(file);
    file.detectFileType(function(err) {
        if (err) throw err;
        commandSelf.log("File Type: " + file.fileType);
        commandSelf.log("File Name: " + file.filename);
        commandSelf.log("Full Path: " + file.fullPath);
    });
});
var File = function(filename){
    this.filename = filename;
    this.fullPath = null;
    this.fileType = null;
};
File.prototype.detectFileType = function(cb){
    this.fullPath = path + "/" + this.filename;
    var self = this;
    // Make sure this is an appropriate image file type
    magic.detectFile(this.fullPath, function(err, result){
        self.fileType = "test"
        cb(err);
    });
}

最新更新