W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
在一個冗長的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有兩個主要用例。記住這是基本上合成糖,使你的生活更輕松。
<?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),以減少意外行為的可能性。
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: