Promise API - Does wait() work?

38 views
Skip to first unread message

jc...@migrate.io

unread,
May 2, 2013, 5:04:50 PM5/2/13
to rin...@googlegroups.com
There aren't any tests for it, so I tried writing a quick example. Perhaps I don't understand how it should work, but this wait() will eventually time out, and value is undefined.

var {Deferred} = require( 'ringo/promise' );

var deferred = new Deferred();

setTimeout( function () {
    deferred.resolve( 'hello world' );
}, 1000 );

var value = deferred.promise.wait( 5000 );

print( 'Value: ' + value );

Any thoughts?

Also, shouldn't a lock timeout throw an exception instead of returning undefined, or is this the customary contract for Promises?

James Cook

unread,
May 3, 2013, 9:59:21 AM5/3/13
to rin...@googlegroups.com
I added some print statements to the RingoJS code to follow the threads. The promise.wait() function is blocking the main thread as I would expect it to. 

The problem is the setTimeout() function also runs on the main thread and is also blocked. I was expecting setTimeout to create a new thread while its delay period ticked down, but this is not the case. The new thread is only created _after_ the delay.

Surprisingly, using a delay of 0 does not work either. I don't yet understand this because the setTimeout function should have created its new thread and started it before promise.wait() is invoked.

So, instead of using setTimeout() to resolve the deferred I handle the threading myself. I don't know if there would be side-effects to changing setTimeout() or if it is possible in the new worker paradigm, but its current behavior seems a bit counterintuitive to me.

var {Deferred} = require( 'ringo/promise' );

var deferred = new Deferred();

function newTimeout( f, delay ) {
    new java.lang.Thread( new java.lang.Runnable({
        run: function() {
            java.lang.Thread.sleep(delay);
            f.call(this);
        }
    }) ).start();
}

newTimeout( function () {
    deferred.resolve( 'hello world' );
}, 1000 );

var value = deferred.promise.wait( 5000 );

print( 'Value: ' + value );

si...@nekapuzer.at

unread,
May 4, 2013, 3:44:32 AM5/4/13
to rin...@googlegroups.com
Maybe this is more a problem with our current promise/deferred implementation than with
setTimeout/interval.

as you have already discovered: setTimeout/interval do not create a new thread, instead they schedule
function calls in the event loop of the current worker. promise.wait() blocks the current worker's
thread, so those scheduled function calls we not happen (not until wait() stopped blocking us).

i would definitely file an issue for this unexpected behaviour... bug or not.

simon
Reply all
Reply to author
Forward
0 new messages