logicalsteps / async
async await implementation using generator function in php
Installs: 1 027
Dependents: 1
Suggesters: 0
Security: 0
Stars: 4
Watchers: 4
Forks: 2
Open Issues: 0
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-10-28 17:57:22 UTC
README
Simplify your asynchronous code and make it readable like synchronous code. It works similar to Async and await in other languages such as JavaScript and C#
It can be used standalone with callback functions. It also works with the promise interface of the following frameworks
It can do cooperative multitasking with the event loop interfaces of the following frameworks
Installation
Async can be installed with Composer by adding it as a dependency to your project's composer.json file. It can be done using the following command.
composer require logicalsteps/async
Please refer to Composer's documentation for more detailed installation and usage instructions.
Usage
Consider the following example
<?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);
If it is all synchronous, our function will simply be
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));
With Async library it can be written as the following
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');
Now the code is clean and looks synchronous, but runs asynchronously for better performance getting us best of both worlds :)
For more examples and integration with the frameworks take a look at examples folder