0

I'm new to Javascript, how I get the return of function isImage() and use the result in function onFileSelect(). I'm trying to get the result but gives value undefined for this.isImage()

isImage(file: File) {
    var reader = new FileReader();
    reader.onload = function(event) {
        var contents = reader.result;
        var buf = new Uint8Array(contents);
        if(buf[0] === 0xFF && buf[1] === 0xD8 && buf[2] === 0xFF){
            console.log("jpg") //jpg
            return true //the true value is not returning
        }else{
            return false
        }
    };
    reader.readAsArrayBuffer(file);
}

onFileSelect(event){
    this.files = event.dataTransfer ? event.dataTransfer.files : event.target.files;        
    if(this.isImage(this.files[0])) {
        //if true...
    }
}

1 Answers1

0

The reason you are not getting a value back is because isImage has some file IO logic which is asynchronous. The way to handle this is to pass isImage a callback (cb). When you have the result of isImage you call the callback function and then the execution happens in the block I commented in.

isImage(file: File, cb) {
    var reader = new FileReader();
    reader.onload = function(event) {
        var contents = reader.result;
        var buf = new Uint8Array(contents);
        if(buf[0] === 0xFF && buf[1] === 0xD8 && buf[2] === 0xFF){
            console.log("jpg") //jpg
            cb(true); //the true value is not returning
        }else{
            cb(false);
        }
    };
    reader.readAsArrayBuffer(file);
}

onFileSelect(event){
    this.files = event.dataTransfer ? event.dataTransfer.files : event.target.files;        
    this.isImage(this.files[0], function(res) {
        // do something with return value here.
    })
}
httpNick
  • 2,524
  • 1
  • 22
  • 34