zee
zee

Reputation: 666

JavaScript - Set object property in callback

I'm pretty confident that there is something with this that I'm doing wrong. This question has been asked before, but even after reviewing the other questions and answers, I still can't get it to work.

Basically the issue is that I can't set file.fileType to be the value I need it to be from within the callback function within 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"
    });
}

Upvotes: 0

Views: 1858

Answers (1)

mscdex
mscdex

Reputation: 106726

A more appropriate solution would be to have detectFileType accept a callback or return a Promise so that you know when the asynchronous task has completed and you can safely check the File instance properties. For example:

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);
    });
}

Upvotes: 1

Related Questions