Skip to content

Instantly share code, notes, and snippets.

@AvinashDalvi89
Created December 4, 2020 09:56
Show Gist options
  • Save AvinashDalvi89/0c0c3f554ad6da3931b2463b2bfb32b2 to your computer and use it in GitHub Desktop.
Save AvinashDalvi89/0c0c3f554ad6da3931b2463b2bfb32b2 to your computer and use it in GitHub Desktop.
Implement async call in PHP using guzzle promise
<?php
use GuzzleHttp\Promise\Promise;
use GuzzleHttp\Promise\EachPromise;
function promiseFunction($sample_array,$index){ // index is optional params
$promise = new Promise(
function () use ($sample_array,$index,&$promise) {
$response = secondFunction($sample_array);
$promise->resolve($response);
},
function ($sample_array,$index,&$promise) {
// do something that will cancel the promise computation (e.g., close
// a socket, cancel a database query, etc...)
$promise->reject($index); // just to know which index has failed or rejected.
}
);
return $promise;
}
function sampleFunction($sample_array_set){
$promises = array();
foreach($sample_array_set as $index => $sample_array){
$promises[$index] = promiseFunction($sample_array,$index);
}
$eachPromise = new EachPromise($promises, [
// how many concurrency we are use
'concurrency' => count($promises), // can set to 4 ,10,20 depend on how many iteration but better to used same as count
'fulfilled' => function ($response,$index) use (&$sample_array)
{
//logic for other operation.
},
'rejected' => function ($reason) {
}
]);
}
$sample_array_set = array('One','Two','Three', 'Four', 'Five', 'Six', 'Seven', 'Eight');
sampleFunction($sample_array_set);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment