logicalsteps / async
使用生成器函数在PHP中实现async await
2.0.0
2020-08-28 08:59 UTC
Requires
- php: >=7.2
- ext-json: *
- psr/log: ^1.0
- react/promise: ^2.8
Requires (Dev)
- amphp/amp: ^2.4
- amphp/http-client: ^4.3
- amphp/socket: ^1.1
- clue/block-react: ^1.3
- clue/buzz-react: ^2.4
- pdepend/pdepend: ^2.7
- php-http/curl-client: ^1.7
- phploc/phploc: ~4.0
- phpmd/phpmd: ^2.8
- phpunit/phpunit: ~7.3
- psy/psysh: ^0.10.3
- react/event-loop: ~1.0
- scrutinizer/ocular: ^1.7
- sebastian/phpcpd: ~4.1
This package is auto-updated.
Last update: 2024-08-28 17:27:32 UTC
README
简化您的异步代码,使其像同步代码一样易于阅读。它与其他语言(如JavaScript和C#中的Async和await)类似
它可以与回调函数独立使用。它还支持以下框架的promise接口
它可以与以下框架的事件循环接口进行协作式多任务处理
安装
可以使用Composer安装Async,将其作为项目composer.json文件中的依赖项添加。可以使用以下命令完成。
composer require logicalsteps/async
有关更详细的安装和使用说明,请参阅Composer文档。
用法
考虑以下示例
<?php require __DIR__ . '/../vendor/autoload.php'; use Web3\Web3; //installed with `composer require sc0vu/web3.php` on the commandline function balance($accountNumber) { $web3 = new Web3('http://localhost:8545'); $eth = $web3->eth; $eth->accounts(function ($error, $result) use ($eth, $accountNumber) { if ($error) { return; } $accounts = $result; $eth->getBalance($accounts[$accountNumber], function ($error, $result) { if ($error) { return; } var_export((int)$result->value); }); }); } balance(0);
如果全部是同步的,我们的函数将简单为
function balance($accountNumber) { $web3 = new Web3('http://localhost:8545'); $eth = $web3->eth; $accounts = $eth->accounts(); $balance = $eth->getBalance($accounts[$accountNumber]); return (int)$balance->value; } var_export(balance(0));
使用Async库可以写成以下形式
use LogicalSteps\Async\Async; use Web3\Web3; function balance($accountNumber) { $web3 = new Web3('http://localhost:8545'); $eth = $web3->eth; $accounts = yield [$eth, 'accounts']; $balance = yield [$eth, 'getBalance', $accounts[$accountNumber]]; $value = (int)$balance->value; return $value; } Async::await(balance(0))->then('var_export');
现在代码看起来很干净,就像同步代码一样,但以异步方式运行,以获得更好的性能,实现了两全其美 :)
有关更多示例和框架集成,请参阅示例文件夹