codecamp

Async Vs Awaitable

一个常见的问题是为什么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> {
    // ...
  }
}


Generators
Guidelines
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }