# Copyright 2001-2004 Six Apart. This code cannot be redistributed without
# permission from www.movabletype.org.
#
# $Id: Promise.pm,v 1.2.2.1 2004/05/13 00:57:44 ezra Exp $

package MT::Promise;
use Exporter;
*import = \&Exporter::import;
@EXPORT_OK = qw(delay force);

sub new {
    my ($class, $code) = @_;
    my $this = \$code;
    bless $this, $class;
}

sub delay {
    my ($this) = @_;
    __PACKAGE__->new($this);
}

sub force {
    my ($this) = @_;
    return $this if (ref $this ne 'MT::Promise');
    if (ref $$this eq 'CODE') {
	$$this = $$this->();
    } else {
	return $$this;
    } 
}

sub test {
    $la_promesse = delay(sub { sleep 10; "a simple value" });

    print $la_promesse->force, "\n";     # takes a long time
    print $la_promesse->force, "\n";     # returns quickly

    # force() works on undefined values...
    $la_promesse_mal = undef;
    print force($la_promesse_mal);
    #    ...and hard references
    $la_promesse_mal = ["venue", "bien"];
    print @{force($la_promesse_mal)}, "\n";
    #    ...and promise objects
    $la_promesse_mal = delay(sub{ ["bien", "venue"] });
    print @{force($la_promesse_mal)}, "\n";
}

1;
