lundi 10 mai 2021

How to do a sequential for loop in Ember.js?

I am using ember 2.1 and I would to apply an action for every line of a text file that I get using the Javascript FileReader api. Would anyone know how to do that?

-When I try using "foreach" the execution is not sequential: the program does not wait for one line to be recorded before starting treating the next line; hence I get lines skipped and have no control on the execution;
-I tried a simple for loop, but it didn't work and I read that they are not possible in Ember actions;
-When I use a recursive call to an Ember action (in the following code: saveNew(lines), called first by openFile(event)), another problem happen: every new line replaces the last one instead of being added to the last one, and at the end only the last line is recorded.

saveNew(lines) {
  
   const promise1 = new Promise((resolve, reject) => {

      var line=lines.shift();
      var cols = line.split(';');      
      var c=0;
      var patt = /[A-z ]/g;
      var result = patt.test(line);
      if (result==true) {
           
         this.model.name=cols[0]; console.log("named");
         this.model.url=cols[1]; console.log("urled");
         this.model.description=cols[2]; console.log("descripted"); console.log(cols[2]);
         this.get('model').save().then((source) => { console.log("in the insertion");
          
           this.send('toast', 'Source créée.'); console.log("wooouu");
          this.transitionToRoute('signed-in.sources.source', source); console.log("incredible");

      }).then(() => {setTimeout(() => {
    resolve(lines);
  }, 1000);
}); }
      else {resolve(lines);}
});

promise1.then((value) => {
  if (value.length>0) {this.send('saveNew',value);}
});
},

openFile(event) {

    console.log('upload');
    var input = event.target;
    var reader = new FileReader();
    console.log('ici');

    reader.addEventListener("load", ( function (e) {
        var text = e.target.result;
    text.replace(/(\r\n)|\r|\n/g, '\n');   //normalisation des caractères de retour à la ligne
    var lines = text.split(/\n+/g);  //séparation du texte du fichier en lignes
    var insnumb=0;
    const taille=lines.length;
    this.send('saveNew',lines);
      }).bind(this));
    reader.readAsText(input.files[0]);
  }



Aucun commentaire:

Enregistrer un commentaire