Async Vs Awaitable

2018-10-11 11:25 更新

一個常見的問題是為什么async返回的函數(shù)需要關鍵字Awaitable。該關鍵字是必需的,因為可以具有返回等待的non-async函數(shù) async關鍵字僅僅是一個實現(xiàn)細節(jié)。因此,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功能實現(xiàn):

<?hh

namespace HHVM\UserDocumentation\Async\Examples\AsyncVsAwaitables;

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

它也可以通過non-async功能實現(xiàn):

<?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

公眾號
微信公眾號

編程獅公眾號