Working with js.lib.Promise

Hello :).

I have a function that returns js.lib.Promise<Void>

When I define the function for then, it asks me to give it at least 1 argument of type Void.

promise.then((a: Void) -> {});

I don’t understand the utility of this argument here.

The signature of then is:

function then<TOut>(onFulfilled:Null<PromiseHandler<T, TOut>>, ?onRejected:PromiseHandler<Dynamic, TOut>):Promise<TOut>;

My Promise is indeed for a function that returns void, but why have that as an argument in the function?

A side-question: in the then signature above, why do we have a T and a TOut?

I don’t think that Void is valid as a “value” in Haxe, so it can’t be used as return value in a js promise. In similar cases I use a bool instead: js.lib.Promise<Bool> and return true (js.lib.Promise.resolve(true)) instead…

1 Like

There’s no utility to the argument there, it’s there because of a “limitation” of Haxe’s type system. There’s no way (as far as I know) to define a generic argument that may be Void (meaning that you can’t make a function that may or may not take an argument depending on it’s generic type).

So in Haxe you can’t really use Promise<Void>, instead you could use Promise<Dynamic> and ignore the argument in the then function.

Regarding the side question, keep in mind that the .then method returns a new promise that resolves to whatever the function you pass to it evaluates to. So you can use then to map a promise into a different type or even to chain promises.

If you are targetting just javascript and using promises I recommend you take a look at hx-jsasync (a lib I made and maintain)

1 Like

I have used import js.lib.Promise; in a port, perhaps it’s useful, you can compare with the JS version.
The signatures needed to vary from the ported code to implement in Haxe, but was still able to get the same functionality.
Perhaps these are useful for learning/ideas?

Best Justin

1 Like