haxetink / tink_await

Haxe async/await
MIT License
58 stars 15 forks source link

How to use it? #19

Closed posxposy closed 6 years ago

posxposy commented 6 years ago

Hey ;)

With this code:

    @:async private function someFunc(url:String):String {
        var f:FutureTrigger<String> = Future.trigger();
        MyHttp.call(url, function(data:String):Void {
            f.trigger(data);
        }, function(error:String):Void {
            f.trigger(data);
        });

        return f.asFuture();
    }

    function new() {
       var result:String = @await someFunc("google.com");
       trace(result);
    }

I got an error: tink.core.Future<String> should be String

If I change it to

@:async private function someFunc(url:String):Future<String>
(...)
var result:Future<String> = @await someFunc("google.com");

then it compiles ok, but how to get my result as String and not as Future? Thanks.

kevinresol commented 6 years ago

did you put @:await on your class?

posxposy commented 6 years ago

Yes, I am. That did not helped.

kevinresol commented 6 years ago

The problem is that:

  1. you should not return a Future manually in a function tagged with @:async, just return the plain type (String in your case)
  2. you need to tag a function with either @:async or @:await so that its content will be transformed. In your case the constructor is not tagger so that the @await inside it won't do anything.

The following code should work.

using tink.CoreApi;

@:await
class Main {

    function f() {
        var trigger = Future.trigger();
        trigger.trigger('hello');
        return trigger.asFuture();
    }

    @:await function new() {
        var s = @:await f();
        trace(s);
    }

    static function main() {
       new Main();
    }
}
posxposy commented 6 years ago

Ah, thank you, thats help me a lot! Got it to work now.