Actionscript 3 在AS3中,将文本文件加载到字符串中

Actionscript 3 在AS3中,将文本文件加载到字符串中,actionscript-3,asynchronous,Actionscript 3,Asynchronous,我一直在尝试将文本文件加载到字符串变量中。名为text.txt的文本文件包含successful。代码如下: public class Main extends Sprite { private var text:String = "text"; private var textLoader:URLLoader = new URLLoader(); public function Main() { textLoader.addEventListener(

我一直在尝试将文本文件加载到字符串变量中。名为
text.txt
的文本文件包含
successful
。代码如下:

public class Main extends Sprite
{
    private var text:String = "text";
    private var textLoader:URLLoader = new URLLoader();

    public function Main() {
        textLoader.addEventListener(Event.COMPLETE, onLoaded);
        function onLoaded(e:Event):void {
            trace("Before 1: " + text); //output: text
            trace("Before 2: " + e.target.data); //output: successful
            text = e.target.data;
            trace("After 1: " + text); //output: successful - yay!!! it worked

        }

        textLoader.load(new URLRequest("text.txt"));

        trace("After 2: " + text); //output: text - what??? nothing happened??? but it just worked

    }

}
输出:

在2之后:文本
1之前:文本
2号之前:成功

1:成功后

您将面临同步与异步问题

当调度
事件时,
textLoader
异步调用函数
onload
,而不是在
textLoader.load
之后直接调用

您必须记住的是
textLoader。load
是非阻塞的,这意味着
“2”
之后可能(您可以假设总是)在
加载之前执行

如果在回答的这一点上,您仍然感到困惑,我会说加载一个文件需要时间,执行一条指令的时间可能会有所不同,但通常比加载一个文件所需的时间要短得多(假设这个文件有4go大)。您无法预测将发生什么,可能磁盘已经很忙,您可能需要等待!但是,您可以利用这宝贵的时间做一些完全独立于文本文件的其他事情,这就是为什么有时编程语言会异步创建它(
php
,例如,同步加载文件)

下一步


既然我已经解释了
“2”之后的
实际上并不存在,那么您必须使用
“1”之后的

作为一个入口点,但是没有任何东西可以帮助您创建一个名为
afterLoad
的函数,您可以这样调用它

public function Main() {
        textLoader.addEventListener(Event.COMPLETE, onLoaded);

        function onLoaded(e:Event):void {
            trace("Before 1: " + text); //output: text
            trace("Before 2: " + e.target.data); //output: successful
            text = e.target.data;
            afterLoad();
        }

        textLoader.load(new URLRequest("text.txt"));
    }


}

private function afterLoad():void {
    trace("After: " + text); // it should work now :)
}

那么我该怎么办呢?但是我以后能得到它(加载的文本)吗?关键是你必须通过
afterLoad
或者直接在
onload
里面。唯一的替代方法是在main就绪时使用自定义事件进行调度,但这是多余的。您可以将
afterLoad
重命名为
MainWithDataLoaded
,如果这有助于您理解此问题的核心是什么。OK。我得到了它。因此,现在我将剩下的代码写入
afterLoad()
-
MainWithDataLoaded()
而不是
Main()