Javascript - use FileReader with Promises

0
    var reader = new FileReader(),
        file1 = new Blob(['Hola'],{type : 'text/plain'}),
        file2 = new Blob(['Mundo'],{type : 'text/plain'}),
        result = null;

     reader.addEventListener('load',function(event){
        result = this.result;
     });

reader.readAsText(file1);

var interval = setInterval(function(){
 if(reader.readyState === 2){
  clearInterval(interval);
    reader.readAsText(file2);
  }
},100);

Suppose I need to read 2 files sequentially with the same FileReader instance, so to avoid getting an error "DOMException: Failed to execute 'readAsText' on 'FileReader': The object is already busy reading Blobs. " so what I do is use a setInterval and it is checking every 100 milliseconds if the readyState reader property is equal to 2 (DONE) and then there if you read the other file .

However I would like to know how I can achieve something similar using promises since I tried it and the truth is that I could not get the fact of reading a file, wait for it to end and then there if start reading another with the same instance of FileReader (I really do not care if it is worse to try to do it synchronously I just want to know how to do this using promises and if I can somehow replace the "listeners" (load, loadstart, progress, loadend etc ...) by promises)

    
asked by akira94 04.05.2017 в 22:19
source

2 answers

0

You can try to use this code, I really have not tried it.

    function readFile(file) {
    var reader = new FileReader();
    var deferred = $.Deferred();

    reader.onload = function(event) {
        deferred.resolve(event.target.result);
    };

    reader.onerror = function() {
        deferred.reject(this);
    };

    if (/^image/.test(file.type)) {
        reader.readAsDataURL(file);
    } else {
        reader.readAsText(file);
    }

    return deferred.promise();
}

This is the link to the repo

    
answered by 04.05.2017 в 23:00
0

To answer your question I created the readFile() function, which returns a promise. This promise, through its method then() returns the contents of the file when it has been loaded and calls the function readFile() again to read the next file

let file1 = new Blob(['Hola'],{type : 'text/plain'}),
    file2 = new Blob(['Mundo'],{type : 'text/plain'}),
    result = null;


function readFile(file){
  return new Promise((resolve,reject) => {
    let reader = new FileReader()
    reader.onload = function(){
      resolve(this.result)
    }
    reader.readAsText(file)
  })
}

readFile(file1).then(data => {
  console.log('Se leyo el archivo 1')
  console.log(data)
  readFile(file2).then(data => {
    console.log('Se leyo el segundo archivo')
    console.log(data)
  })
})
    
answered by 09.05.2017 в 01:18