最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

raku - Writing async routines: use `start` or `Promise.then`? - Stack Overflow

programmeradmin3浏览0评论

I'm looking for the right way to write asynchronous routines. Here's a hypothetical example of some asynchronous javascript function:

async function someFunction() {
    const data = await Promise.resolve(42);             // await some async job
    const secondData = isPrime(data);                   // do some sync job
    await Promise.resolve();                            // await another async job
    const result = secondData === false ? 'ok' : 'err'; // do another sync job
    return result;                                      // return result
}

As far as I understand, in Raku we can make a routine asynchronous by just wrapping it in start { }, or we can use chained promises. Actually, I wrote a simple benchmark to compare these two approaches:

sub test-start { start {
    my $data := await Promise.kept(42);
    my $second-data := $data.is-prime;
    await Promise.kept;
    my $result := $second-data == False ?? 'ok' !! 'err';
    $result;
} }
sub test-then {
    Promise.kept(42).then({
        my $data := $_.result;
        my $second-data := $data.is-prime;
        Promise.kept.then({
            my $result := $second-data == False ?? 'ok' !! 'err';
            $result;
        }).result;
    })
}

race for ^100000 {
    die if test-start.result ne 'ok';
}
say "{now - INIT now} seconds using 'start'";
my $now = now;
race for ^100000 {
    die if test-then.result ne 'ok';
}
say "{now - $now} seconds using 'then'";

On my machine the result is:

8.638755866 seconds using 'start'
4.660412604 seconds using 'then'

It seems that chained promises are faster, but the code becomes more convoluted. So, there are two questions:

  1. Is using chained promises really faster nowadays, or is my benchmark misleading?
  2. Rakudo is constantly evolving and various optimizations are made. Can we expect the first approach to match the speed of the second in the future, or will chained promises always remain faster due to some fundamental reason?
发布评论

评论列表(0)

  1. 暂无评论