如何在其范围之外访问 Guzzle 的完整响应?

How to access Guzzle's fullfilled response outside its scope?

我是 guzzle 包的新手,我正在使用 pool-promise 方法通过它发送异步 post 请求。一切都很好,但是一旦请求得到满足并收到响应,我试图将 json 响应的某些部分存储在数组 $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

请帮助我了解它的工作原理。

编辑:使用 postman,我得到的响应格式如下 json:

{"status":true,"message":"Mnemonics fetched successfully",....SOME OTHER KEYS ETC }

在找到解决方案时回答我自己的问题。

如果你想在匿名函数中设置变量,使用&$VariableName,在我的例子中是:

'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'];


            },

我希望像我这样的人会喜欢这个有用的答案。