Haxe 3 promises with promhx

Posted on June 14, 2013



Wikipedia about Promises:

In computer science, future, promise, and delay refer to constructs used for synchronizing in some concurrent programming languages. They describe an object that acts as a proxy for a result that is initially unknown, usually because the computation of its value is yet incomplete.

The use of promises can greatly simplify handling of asynchronous tasks, and thanks to Justin Donaldson’s promhx library  we now have a easy to use implementation for Haxe 3. It’s built on top of Juraj Kircheim’s great tinkerbell libraries tink_core and tink_macro. Thank you, Justin and Juraj!

Here’s a simple example on how to handle asynchronous stuff. Two asynchronous processes are set up, and a handler to be called when they are both resolved. It should compiler as-is for flash or js targets. (No problem using neko, except for that the neko platform doesn’t have the Timer.delay method.)

package ;

import haxe.Timer;
import promhx.Promise.Promise;

// To be compiled with Haxe 3 for flash or js target
// Required libraries:
// > haxelib install tink_core
// > haxelib install tink_macro
// > haxelib install promhx

class Main
    static function main()
        // Set up two async processes, each returning a promise
        var a = asyncPromiseReturningRandomInt(500);
        var b = asyncPromiseReturningRandomInt(2000);

        // Add a handler to be called when both async processes are resolved
        Promise.when(a, b).then(function(aValue, bValue) {
            trace('Both promises resolved! Sum: ${aValue + bValue}');

    // Example async process
    static function asyncPromiseReturningRandomInt(timeoutMs:Int) : Promise<Int>
        var p = new Promise<Int>();
        Timer.delay(function() {
            var randomInt = Std.int(Math.random() * 100);
            trace('Resolve promise with random value $randomInt');
        }, timeoutMs);
        return p;

In real life the async process could wrap, say, a http request that would be resolved when the data has finished loading. Have a look at Justin’s demo, including error handling: https://github.com/jdonaldson/promhx/blob/master/demo/DemoUtils.hx (Note that this is js target stuff.)


Posted in: Haxe, Uncategorized