jdonaldson / promhx

A promise and functional reactive programming library for Haxe
MIT License
145 stars 24 forks source link

JS Style Chaining #89

Open ianharrigan opened 2 years ago

ianharrigan commented 2 years ago

Is there a way, using this lib, to have js type chaining of promises, for example (in js, well haxe -> js):

js_task1(3).then(n -> {
    trace("js done 1:", n);
    return js_task2(n);
}).then(n -> {
    trace("done 2:", n);
    trace(n);
}).catchError(e -> {
    trace("e:", e);
});

private function js_task1(n:Int):js.lib.Promise<Int> {
    return new js.lib.Promise(function(resolve, reject) {
        trace("in js task 1: ", n);
        resolve(n * 101);
    });
}

private function js_task2(n:Int):js.lib.Promise<Int> {
    return new js.lib.Promise(function(resolve, reject) {
        trace("in js task 2", n);
        resolve(n * 102);
    });
}

this outputs as you would expect:

src/MainView.hx:55: in js task 1: , 3
src/MainView.hx:29: js done 1:, 303
src/MainView.hx:62: in js task 2, 303
src/MainView.hx:32: done 2:, 30906
src/MainView.hx:33: 30906

However, when i try to do similar with this lib:

task1(2).then(n -> {
    trace("done 1:", n);
    return task2(n);
}).then(n -> {
    trace("done 2:", n);
    trace(n);
}).catchError(e -> {
    trace("e:", e);
});

private function task1(n:Int):Promise<Int> {
    trace(" in task 1");
    var d = new Deferred();
    d.resolve(n * 101);
    return d.promise();
}

private function task2(n:Int):Promise<Int> {
    trace(" in task 2");
    var d = new Deferred();
    d.resolve(n * 102);
    return d.promise();
}

I get the following:

src/MainView.hx:37: in task 1, 2
src/MainView.hx:14: done 1:, 202
src/MainView.hx:44: in task 2, 202
src/MainView.hx:17: done 2:, {
    _resolved : true, 
    _pending : true, 
    _errorPending : false, 
    _fulfilled : false, 
    _update : [], 
    _error : [], 
    _errored : false, 
    _rejected : false
}
src/MainView.hx:18: {
    _resolved : true, 
    _pending : true, 
    _errorPending : false, 
    _fulfilled : false, 
    _update : [], 
    _error : [], 
    _errored : false, 
    _rejected : false
}

Am i just using the promises (from this lib) totally wrong? Or is this not a pattern that is supported?

Many thanks! Ian