JavaScript - 在回调中设置对象属性

时间:2016-09-09 01:29:24

标签: javascript callback mmmagic

我非常确信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"
    });
}

1 个答案:

答案 0 :(得分:1)

更合适的解决方案是让detectFileType接受回调或返回Promise,以便您知道异步任务何时完成,并且您可以安全地检查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);
    });
}