0
function foo(){
    var filename="xxx.txt";   
    var readtxt;
    var file = Cc["@mozilla.org/file/directory_service;1"].
            getService(Ci.nsIProperties).
            get("Home", Ci.nsIFile);
    file.append(filename);
    NetUtil.asyncFetch(file, function(inputStream, status) {
        if (!components.isSuccessCode(status)) {
            // Handle error!
            console.log("file read error.."+filename);
            return;
        }
        // The file data is contained within inputStream.
        // You can read it into a string with
        readtxt = NetUtil.readInputStreamToString(inputStream, inputStream.available());
        console.log("firstly print="+readtxt);
    });
    console.log("secondly print="+readtxt);
}

The purpost of the code is to read from a file and then print it. In the above code, I define a var readtxt. Then in line console.log("firstly print="+readtxt);, readtxt is successfully printed. However, in line console.log("secondly print="+readtxt); it says secondly print=undefined. I don't know why.

augustoccesar
  • 658
  • 9
  • 30
kennn9
  • 51
  • 3
  • A little tip: using proper indentation always helps when sorting out scope issues. – Álvaro González Nov 18 '14 at 13:23
  • Does the second print appear in the console *before* the first print? – Alex K. Nov 18 '14 at 13:24
  • 1
    `NetUtil.asyncFetch` - the **async** is the important part here ... – Sirko Nov 18 '14 at 13:24
  • second print appears after first print – kennn9 Nov 19 '14 at 00:33
  • Second print cannot be guranteed to happen before the `firstly print`. Its an async function which means that it works like `setTimeout(function() { readtxt = 'hi' }, 5000)` except that `5000` in this example doesnt apply to your case, it does it as fast as it can but this is usually longer than it takes to get to the next line. – Noitidart Nov 19 '14 at 09:27

0 Answers0