Can I get a return value outside of Promise?

37 views
Skip to first unread message

Dingbing Liw

unread,
Aug 4, 2021, 10:24:57 AM8/4/21
to Mojolicious
Hi, all.
I am refactoring my mojolicious app.
Is there any way to use promise and keep the same return value?
For example:

My original  method:
sub some_method {
  my $a = block_function_a();
  my $b = block_function_b();
  my $c = block_function_c();  ### for example many Mojo::Pg search
  return $a+$b+$c;
}

Now I change block_function_c to  an unblocked promise.

sub some_method {
  my $a = block_function_a();
  my $b = block_function_b();
  return promise_mojo_db_search->then(sub($c){ 
       $a+$b+c;
   }
);
}

I have to change many relative code after the return value change.
It is very annoying.
Is there any way to return the same value with promise.

Vincent Tondellier

unread,
Aug 5, 2021, 11:39:01 AM8/5/21
to Mojolicious, Dingbing Liw
Hi,


On 2021-08-04, 11:30:43 CEST Dingbing Liw wrote:
> I am refactoring my mojolicious app.
> Is there any way to use promise and keep the same return value?

You can use async/await for this.

See https://metacpan.org/dist/Mojolicious/view/lib/Mojolicious/Guides/Cookbook.pod#async/await

Your example would be:
sub some_method {
my $a = block_function_a();
my $b = block_function_b();
my $c = await nonblock_function_c();
return $a+$b+$c;
}

where nonblock_function_c can either return a promise or be an async function (see doc)

Mail Delivery Subsystem

unread,
Feb 2, 2022, 8:39:47 AM2/2/22
to Mojolicious
Reply all
Reply to author
Forward
0 new messages