Async Blocks

2018-10-10 11:06 更新

在一個冗長的Async功能中,通常一個好主意將與其余功能無關(guān)的數(shù)據(jù)讀取分組在一起。這減少了不必要的等待I / O。

為了將這個分組內(nèi)聯(lián),你通常必須使用一個幫助函數(shù)。Async Blocks允許立即執(zhí)行代碼分組,可能在零參數(shù),Async lambdas中。

語法

Async Blocks的語法是:

async {
  // grouped together calls, usually await.
  < statements >
}

用法

Async Blocks有兩個主要用例。記住這是基本上合成糖,使你的生活更輕松。

  • 在需要一個函數(shù)調(diào)用執(zhí)行之前的內(nèi)聯(lián)簡單Async語句。
  • 替換async lambda所需的調(diào)用返回一個實際的Awaitable<T>。
<?hh

namespace Hack\UserDocumentation\Async\Blocks\Examples\SyntaticSugar;

async function gen_int(): Awaitable<int> {
  return 4;
}

async function gen_float(): Awaitable<float> {
  return 1.2;
}

async function gen_string(): Awaitable<string> {
  return "Hello";
}

async function gen_call<Tv>((function (): Awaitable<Tv>) $gen): Awaitable<Tv> {
  return await $gen();
}

async function use_async_lambda(): Awaitable<void> {
  // To use an async lambda with no arguments, you would need to have a helper
  // function to return an actual Awaitable for you.
  $x = await gen_call(
    async () ==> {
      $y = await gen_float();
      $z = await gen_int();
      return round($y) + $z;
    }
  );
  var_dump($x);
}

async function use_async_block(): Awaitable<void> {
  // With an async block, no helper function needed. It is all built-in to the
  // async block itself.
  $x = await async {
    $y = await gen_float();
    $z = await gen_int();
    return round($y) + $z;
  };
  var_dump($x);
}

async function call_async_function(): Awaitable<void> {
  // Normally you have to call a simple async function and get its value, even
  // if it takes no arguments, etc.
  $x = await gen_string();
  var_dump($x);
}

async function use_async_block_2(): Awaitable<void> {
  // Here you can inline your function right in the async block
  $x = await async { return "Hello"; };
  var_dump($x);
}

\HH\Asio\join(use_async_lambda());
\HH\Asio\join(use_async_block());

\HH\Asio\join(call_async_function());
\HH\Asio\join(use_async_block_2());

Output

float(5)
float(5)
string(5) "Hello"
string(5) "Hello"

限制

類型檢查器不允許==>在lambda 的右側(cè)立即使用異步塊。

在使用function關(guān)鍵字聲明的Async函數(shù)中,async緊接在前面function,而這些緊跟在參數(shù)之前。在異步lambdas中,async也立即在參數(shù)之前。

所以:

$ x = async()==> {...} // good 
$ x =()==> async {...} // bad  

基本上這只是一個安全警衛(wèi),以減少意外行為的可能性。


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號