Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Making a Promise

by Anonymous Monk
on Oct 05, 2015 at 14:37 UTC ( [id://1143821]=perlquestion: print w/replies, xml ) Need Help??

Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hello Monks, I'm working on some asynchronous code and have started using the Promises module. I'm using collect to gather the results of several operations, but am not sure how to wrap a non-async function so that it returns a Promise object. The following example does not work:
my $d = deferred->new; my $result = External::Parser->run( '--in', $file ); $result ? $d->resolve( $result ) : $d->reject(); $d->promise;

Replies are listed 'Best First'.
Re: Making a Promise
by Corion (Patriarch) on Oct 05, 2015 at 14:51 UTC

    In what sense does your snippet as shown not work?

    Can you wrap the snippet in a small (20 lines) self-contained program that shows the problem?

    Note that the call to External::Parser->run will always have happened before your function returns. This is different from the example in Promises because the http_get function is an asynchronous function which invokes the callback upon completion. If you want to move some arbitrary synchonous code to Promises, I would try to wrap a callback to that code with an object that implements a function ->result that actually calls the synchronous code and returns the result:

    package Promise::Lazy; use parent 'Promises::Promise'; sub new { my( $class, $usercallback ) = @_; my $self = $class::SUPER->new(); $self->{ usercallback } = $usercallback; $self }; sub result { my( $self ) = @_; my $result = $self->{ usercallback }->(); if( $result ) { $self->resolve( $result ) } else { $self->reject(); }; }; ... somewhere in your code ... return Promise::Lazy->new(sub { External::Parser->run('--in', $file); });

      The snippet wasn't working due to an unrelated documentation error -- the constructor for a Promises::Deferred object should have been deferred, not deferred->new. Doh.

      I've implemented a wrapper for the synchronous code similar to your code, and now it's all working as anticipated. Thank you for the help!

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://1143821]
Approved by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (6)
As of 2024-04-20 00:16 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found