Reputation: 880
I am new to guzzle package and I am sending async post requests through it using pool-promise method. Everything is well and good but once the request is fulfilled and response is received, I am trying to store some part of json response in an array $arr
.
$client = new Client();
$arr = [];
$requests = function ($total) use ($client) {
$request_headers = [
'api_key' => config('app.wallet_server_api_key'),
'Content-Type' => 'application/x-www-form-urlencoded'
];
$form_params = [
'accounts' => 0,
'totalaccounts' => 100,
];
$uri = 'MY_REQUEST_URL_CAN_NOT_DISCLOSE';
for ($i = 0; $i < $total; $i++) {
// yield new Request('POST', $uri, $request_headers, http_build_query($form_params, null, '&'));
yield function () use ($client, $uri, $request_headers, $form_params) {
return $client->postAsync($uri, [
'headers' => $request_headers,
'form_params' => $form_params
]);
};
}
};
$pool = new Pool($client, $requests(2), [
'concurrency' => 5,
'fulfilled' => function (Response $response, $index) use ($arr) {
// Response is logged successfully
Log::info(json_decode($response->getBody()->getContents(), true)['message']);
// I am pushing the message key from json response received but it is not taking
$arr[] = json_decode((string)$response->getBody()->getContents(), true)['message'];
},
'rejected' => function (RequestException $reason, $index) {
// this is delivered each failed request
Log::warning(json_encode($reason->getMessage()));
},
]);
// Initiate the transfers and create a promise
$promise = $pool->promise();
// Force the pool of requests to complete.
$promise->wait();
dd($arr); // Displays as null
Please help me understand its working.
EDIT: using postman, I am getting response in json format like below:
{"status":true,"message":"Mnemonics fetched successfully",....SOME OTHER KEYS ETC }
Upvotes: 0
Views: 1174
Reputation: 880
Answering my own question as I found the solution.
If you want to set variable in anonymous function, use &$VariableName
as in my case it is:
'fulfilled' => function (Response $response, $index) use (&$arr) { // <-- see the & sign here
// Response is logged successfully
Log::info(json_decode($response->getBody()->getContents(), true)['message']);
// I am pushing the message key from json response received but it is not taking
$arr[] = json_decode((string)$response->getBody()->getContents(), true)['message'];
},
I hope someone like me will fond this answer useful.
Upvotes: 3