我正在尝试在PHP中使用Guzzle池。但是我在处理ASYNC请求时遇到了困难。以下是代码段。
$client = new \GuzzleHttp\Client();
function test()
{
$client = new \GuzzleHttp\Client();
$request = $client->createRequest('GET', 'http://l/?n=0', ['future' => true]);
$client->send($request)->then(function ($response) {
//echo 'Got a response! ' . $response;
return "\n".$response->getBody();
});
}
$res = test();
var_dump($res); // echoes null - I know why it does so but how to resolve the issue.
有没有人如何让功能等待并获得正确的结果。
答案 0 :(得分:1)
如果你可以退货,它在代码风格上不会异步。退还承诺并在外面打开它。
function test()
{
$client = new \GuzzleHttp\Client();
$request = $client->createRequest('GET', 'http://l/?n=0', ['future' => true]);
// note the return
return $client->send($request)->then(function ($response) {
//echo 'Got a response! ' . $response;
return "\n".$response->getBody();
});
}
test()->then(function($body){
echo $body; // access body here inside `then`
});
答案 1 :(得分:0)
我想使用枪口6,postAsync和Pool共享另一个示例。
function postInBulk($inputs)
{
$client = new Client([
'base_uri' => 'https://a.b.com'
]);
$headers = [
'Authorization' => 'Bearer token_from_directus_user'
];
$requests = function ($a) use ($client, $headers) {
for ($i = 0; $i < count($a); $i++) {
yield function() use ($client, $headers) {
return $client->postAsync('https://a.com/project/items/collection', [
'headers' => $headers,
'json' => [
"snippet" => "snippet",
"rank" => "1",
"status" => "published"
]
]);
};
}
};
$pool = new Pool($client, $requests($inputs),[
'concurrency' => 5,
'fulfilled' => function (Response $response, $index) {
// this is delivered each successful response
},
'rejected' => function (RequestException $reason, $index) {
// this is delivered each failed request
},
]);
$pool->promise()->wait();
}