Async Vs Awaitable

2018-10-11 11:25 更新

一个常见的问题是为什么async返回的函数需要关键字Awaitable。该关键字是必需的,因为可以具有返回等待的non-async函数 async关键字仅仅是一个实现细节。因此,async在接口中不允许。例如:

<?hh

namespace HHVM\UserDocumentation\Async\Examples\AsyncVsAwaitables;

interface Car {
  // It doesn't matter to the caller how this is implemented, only that it
  // returns an Awaitable<void>
  public function drive(): Awaitable<void>;
}

这可以用Async功能实现:

<?hh

namespace HHVM\UserDocumentation\Async\Examples\AsyncVsAwaitables;

class Ford implements Car {
  public async function drive(): Awaitable<void> {
    // ...
  }
}

它也可以通过non-async功能实现:

<?hh

namespace HHVM\UserDocumentation\Async\Examples\AsyncVsAwaitables;

class VolkswagenDiesel implements Car {
  public function drive(): Awaitable<void> {
    $being_tested = class_exists(
      \PHPUnit_Framework_TestCase::class,
      /* autoload = */ false,
    );

    // As these two functions return Awaitable<void>, we can just pass along
    // their Awaitables.
    if ($being_tested) {
      return $this->driveWithCleanEmissions();
    }
    return $this->driveNormally();
  }

  private async function driveWithCleanEmissions(): Awaitable<void> {
    // ...
  }

  private async function driveNormally(): Awaitable<void> {
    // ...
  }
}


以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号