Hello stackoverflow users and readers, I am programming a quite easy thing with JS for Firefox/Gecko 2.x and have reached a problem that is a little far away from my knowledge. The thing is: I read a the content of a file to a string using the following code:
NetUtil.asyncFetch(my_file, function(inputStream, status) {
if (!Components.isSuccessCode(status)) {
return;
}
my_string = NetUtil.readInputStreamToString(inputStream, inputStream.available());
]);
And right after reading the file I evaluate the following condition:
if (my_string.length == 0) {
//do something...
} else {
//do something else...
}
OK, so the problem is, althou开发者_如何学Cgh there are some characters in the file, if it's the first run of the script, it will always go to the first condition because it hasn't got time enough to read the file and load the characters into the string. On a second run, the global variable my_string has the previously acquired value, so it will go into the "else" condition. The question is: How can I listen to a "file finished loading" event in JavaScript to prevent this behaviour? Thank you very much.
as far as fetch is async it's normal my_string to be empty. You need to subscribe for some custom event or pass a callback somehow.
NetUtil.asyncFetch(my_file, function(inputStream, status) {
if (!Components.isSuccessCode(status)) {
return;
}
my_string = NetUtil.readInputStreamToString(inputStream, inputStream.available());
var evt = document.createEvent('Event');
evt.initEvent('inputReady', true, true);
evt.my_string = my_string;
document.dispatchEvent(evt);
});
and then subscribe for this event
document.addEventListener('inputReady', function(e){
alert(e.my_string);
});
P.S. Not tested
hello i am not familiar with NetUtil of Firefox/Gecko 2.x but the concept look familiar.
i assume that is because the
NetUtil.asyncFetch
call to your callback function after the
if (my_string.length == 0) {
//do something...
} else {
//do something else...
}
why not you try using the data in correct place
NetUtil.asyncFetch(my_file, function(inputStream, status) {
if (!Components.isSuccessCode(status)) {
return;
}
my_string = NetUtil.readInputStreamToString(inputStream, inputStream.available());
alert(my_string.length); //is here is also be 0 ???????
//do some stuff with the data
]);
精彩评论