Haxe - How to implement async for Flash Targets

I currently have this code:

package sage.sys;

import com.dongxiguo.continuation.Async;

#if flash
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.net.URLLoaderDataFormat;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.SecurityErrorEvent;
#end

class FileSystem implements Async
{
    public static function fetchText(url:String, callback:String->Void) : Void
    {
        var urlLoader = new URLLoader();
        var onLoaderError = function(e : Event) : Void {
        callback(e.type);
    };

    urlLoader.addEventListener(Event.COMPLETE, function(_) : Void {
        callback(Std.string(urlLoader.data));
    });

    urlLoader.addEventListener(IOErrorEvent.IO_ERROR, onLoaderError);
    urlLoader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onLoaderError);

    try {
        urlLoader.dataFormat = URLLoaderDataFormat.TEXT;
        urlLoader.load(new URLRequest(url));
    }
    catch (e : Dynamic)
    {
        callback(Std.string(e));
    }
}

@async
public static function fetch(url:String):String
{
    var result = @await fetchText(url);
    return result;
}
}

      

When I try to run it, it doesn't wait on hold and returns from the function. How can I get @await to actually provide itself and stop working outside of the function until the value is resolved from the asynchronous call?

Lib used: https://github.com/proletariatgames/haxe-continuation

+3


source to share


2 answers


You can not. The function you call fetchText()

will never "wait" in that sense.

However, according to the "haxe-continueation" documentation, it will put everything after your expression @await FileSystem.fetchText()

into a new function that will be passed as a parameter callback

fetchText()

. So in code it looks like it is waiting.

According to the documentation, you should make sure you put @async

in front of the function that uses fetchText()

. According to this, something like this should work (untested):



@async function someFunction(): Void {
  var result1 = @await FileSystem.fetchText(someUrl);
  var result2 = @await FileSystem.fetchText(anotherUrl);
  trace(result1);
  trace(result2);
}

      

The 2 traces at the end of the function must occur after result1

and result2

have been retrieved, even if someFunction()

actually returned before traces already passed.

It might be helpful to see your code that is calling fetchText()

.

+3


source


How did you use the function fetch

?

I assume you should make a callback: FileSystem.fetch(url, function(result) trace(result));



The call itself fetch

should return immediately as it is asynchronous and the result will be passed to the callback.

I don't think it is possible to do a flash block when calling fetch.

+1


source







All Articles