COMMUNITY

Showcasing JSAsync: Haxe library for generating native JS async/await functions

If you target JS and you are working with js.lib.Promise you can use this library to escape from callback hell in an ergonomic and type-safe way.

Your haxe code will look like this:

@:jsasync static function fetchText(url : String) {
    return "Text: " + Browser.window.fetch(url).jsawait().text().jsawait();
}

fetchText return type will be inferred to js.lib.Promise<String>

And the js output will be this:

static async fetchText(url) {
    return "Text: " + (await (await window.fetch(url)).text());
}

Haxelib: https://master-lib.haxe.org/p/jsasync/
Repo: https://github.com/basro/hx-jsasync

I’m using this on my own projects, I hope that someone else will also find it useful.

8 Likes

Nice one! I would mention in the README that you can also statically import JSAsyncTools.await and use it as a “global” function, e.g.

import JSAsyncTools.await;

//...later
var x = await(somePromise);

Maybe also worth mentioning that one can put this into an import.hx file for convenience. I know it’s pretty generic/basic Haxe stuff but a lot of people don’t actually realize you can do this :slight_smile:

Same with JSAsync.func: I would actually import it with import JSAsync.func as async, so I can do async(function(...) { ... }) later. Maybe it’s worth considering renaming func to async for that :slight_smile:

3 Likes

Great suggestions @nadako.
Since when has it been possible to import static fields? I was not aware of this :stuck_out_tongue:

Another thing: What are the chances of Haxe using async and await as keywords in the future? Perhaps I should avoid those names to ensure it wont break if/when the keywords are added to haxe?

I think static imports was there since Haxe 3, so, for quite a long time.

Regarding async/await, the current proposed coroutine design doesn’t reserve these keywords, because it proposes lower level coroutines and the idea is that async and await functions are implemented by the user on top of them, but it’s not set in stone still, so yeah maybe it’s a good idea to avoid those for now.

I’ve implemented your recommendations, I went for JSAsync.jsasync and JSAsyncTools.jsawait to be safe.

Thank you, Mario! Great library!

You are welcome @cambiata, glad that it is useful to others.