2016-07-28 37 views
1

我在WinJS中有变量作用域的问题。当变量被改变时,它应该在更大范围内可见,但是在调用函数之后,该变量仅在函数内部具有值。我认为这是readTextAsync的问题,因为当我在没有readTextAsync的函数中填充变量时,它正在工作。WinJS变量只在函数内部变化

这是变量声明:

var fileDate; 

这是函数,我调用另一个:

WinJS.UI.Pages.define("index.html", { 
     ready: function (element, options) { 
      loadDate(); 
      console.log("główna " + fileDate); //fileDate = undefined 
      this.fillYearSelect(); 
     }, 

这是函数,其中变量发生变化:

localFolder.getFileAsync(filename).then(function (file) { 
       Windows.Storage.FileIO.readTextAsync(file).done(function (fileContent) { 
       fileDate = fileContent; // example - fileDate=a073z160415 
       console.log("fileDate " + fileDate); 
      }, 
      function (error) { 
       console.log("Reading error"); 
      }); 
     }, 
     function (error) { 
      console.log("File not found"); 
     }); 
    } 

附:对不起我的英语不好。它不完美:)

回答

1

我认为这是readTextAsync的问题,因为当我在没有readTextAsync的函数中填充变量时,它正在工作。

我是从你上一篇文章的代码做出这个答案的。 Windows.Storage.FileIO.readTextAsync是一个Windows异步api。所以应该以异步方式处理:console.log("główna " + fileDate)应该像loadDate().then()一样在下面处理,fileContent应该返回,您可以在loadDate().then(function(data){})中捕获它。

WinJS.UI.Pages.define("index.html", { 
    ready: function (element, options) { 
     loadDate().then(function(data){ 
      fileDate=data; //here catch the fileContent data 
      console.log("główna " + fileDate); 
     }); 
     this.fillYearSelect(); 
    }, 

function loadDate() { 
      var that = this; 
      var filename = "abc.txt"; 
      return Windows.Storage.ApplicationData.current.localFolder.getFileAsync(filename).then(function (file) { 
       return Windows.Storage.FileIO.readTextAsync(file).then(function (fileContent) { 
        return fileContent;//here return the fileContent.You can catch it outside. 
       }, 
       function (error) { 
        console.log("Błąd odczytu"); 
       }); 
      }, 
      function (error) { 
       console.log("Nie znaleziono pliku"); 
      }); 
     } 
+0

它还活着!我必须改变我的代码,但是你的解决方案是非常有用的。谢谢。 –