Skip to content

Instantly share code, notes, and snippets.

@oleksandr-roskovynskyi
Forked from ardani/concurrency.php
Created May 20, 2020 11:49
Show Gist options
  • Save oleksandr-roskovynskyi/d9c258070385404a521fbdaba6694106 to your computer and use it in GitHub Desktop.
Save oleksandr-roskovynskyi/d9c258070385404a521fbdaba6694106 to your computer and use it in GitHub Desktop.
<?php
use GuzzleHttp\Promise\EachPromise;
use GuzzleHttp\Psr7\Response;
$users = ['one', 'two', 'three'];
$promises = (function () use ($users) {
foreach ($users as $user) {
// don't forget using generator
yield $this->getAsync('https://api.demo.com/v1/users?username=' . $user);
}
})();
$eachPromise = new EachPromise($promises, [
// how many concurrency we are use
'concurrency' => 4,
'fulfilled' => function (Response $response) {
if ($response->getStatusCode() == 200) {
$user = json_decode($response->getBody(), true);
// processing response of user here
}
},
'rejected' => function ($reason) {
// handle promise rejected here
}
]);
$eachPromise->promise()->wait();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment