Javascript 的并发问题 - 我需要一种方法来检查文件加载是否已完成
stackoverflow 用户和读者大家好, 我正在用 JS 为 Firefox/Gecko 2.x 编写一个非常简单的东西,但遇到了一个离我的知识有点远的问题。 问题是:我使用以下代码将文件的内容读取为字符串:
NetUtil.asyncFetch(my_file, function(inputStream, status) {
if (!Components.isSuccessCode(status)) {
return;
}
my_string = NetUtil.readInputStreamToString(inputStream, inputStream.available());
]);
读取文件后,我立即评估以下条件:
if (my_string.length == 0) {
//do something...
} else {
//do something else...
}
好的,所以问题是,尽管文件中有一些字符,但如果它是第一次运行脚本时,它总是会进入第一个条件,因为它没有足够的时间来读取文件并将字符加载到字符串中。在第二次运行时,全局变量 my_string 具有先前获取的值,因此它将进入“else”条件。 问题是:如何在 JavaScript 中监听“文件完成加载”事件来防止这种行为? 非常感谢。
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, although 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
就 fetch 而言, my_string 为空是正常的。您需要订阅某些自定义事件或以某种方式传递回调。
然后订阅此
活动未测试
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.
and then subscribe for this event
P.S. Not tested
你好,我不熟悉 Firefox/Gecko 2.x 的 NetUtil,但这个概念看起来很熟悉。
我认为这是因为
之后调用您的回调函数
在您为什么不尝试在正确的位置使用数据
hello i am not familiar with NetUtil of Firefox/Gecko 2.x but the concept look familiar.
i assume that is because the
call to your callback function after the
why not you try using the data in correct place