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

标签 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"
    });
}

最佳答案

更合适的解决方案是让 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);
    });
}

关于JavaScript - 在回调中设置对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39402499/

相关文章:

javascript - 在 React 中使用泛型定义 props

javascript - jquery如何获取容器的属性?

javascript - Vue.js 组件不工作

iOS Swift : Closures (Callbacks) versus Delegates, 什么时候使用哪个?

javascript - 直接调用方法和使用 '.call' 方法的区别? JS

javascript - 回调,错误 : is not a function

typescript - 在 Jest 测试期间无法从 '../build/Release/magic' 找到模块 'index.js'

javascript - Mongoose 在填充后使用 where