2016-10-04 55 views
0

我有以下模型與文件閱讀功能。然而,閱讀是在下一段代碼之後完成的。爲什麼以及如何才能讓它返回文件的讀取內容?如何檢測FileReader負載結束?

TreeContainer = Backbone.Model.extend({ 
       elementCount: 0, 
       file: '', 
       object: {jj: "kk"}, 
       type: "input", 
       parent: d3.select("#canvas"), 
       initialize: function() { 
        var result = this.readFile(); 
        for (var i = 0; i < 200; i++) { 
         console.log(i); //this is resulted before the readFile content 
        } 

       }, 
       readFile: function() { 
        var model = this; 
        // display text 
        if (this.get('file').name.endsWith(".json") || this.get('file').type === "application/json") { 

         var reader = new FileReader(); 

         reader.onload = function (e) { 
          //parseJSON 
          var text = e.target.result; 
          var data = JSON.parse(text); 
          model.set('object', data); 
          console.log(data); 
          return data; 
         }; 
         reader.readAsText(this.get('file')); 
        } 
       } 
      }); 

回答

2

你已經愛上了async for loop problem

您只能在所有文件循環您已經閱讀所有內容 這裏後使用Screw-FileReader

initialize: function(){ 
    this.readFile().then(arr => { 
     for (let json of arr) { 
      console.log(json) //this is resulted before the readFile content 
     } 
    }) 
}, 
readFile: function() { 
    function isJSON(file) { 
     return file.name.toLowerCase().endsWith('.json') || 
     file.type === 'application/json' 
    } 

    return Promise.all(
     Array.from(input.files) 
     .filter(isJSON) 
     .map(file => file.json()) 
    ) 
} 

Alternetive是包裝的FileReader一個例子in a Promise

return new Promise(resolve => { 
    reader.onload = function (e) { 
     var text = e.target.result 
     var data = JSON.parse(text) 
     model.set('object', data) 
     resolve(data) 
    } 
}) 

或發送回撥

initialize: function(){ 
    this.readFile(json => { 
     json 
    }) 
}, 
readFile: function(resolve) { 
    resolve(data) 
}