W3Cschool
恭喜您成為首批注冊用戶
獲得88經驗值獎勵
一個常見的問題是為什么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> {
// ...
}
}
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: