问题
So I'm trying to use guzzle for a couple of concurrent requests. I've seen several examples online and this is what I came up with, but can't seem to get it to work. No errors, no warnings, nothing. I've tried logging inside each promise but nothing happens.
And I know for sure that nothing is happening because nothing is getting inserted in the DB. Any ideas what I'm missing? (I'm yielding each request with its respective then
because at the end of each promise, the DB operations are specific to that user)
use GuzzleHttp\Promise\EachPromise;
use Psr\Http\Message\ResponseInterface;
$promises = (function () use($userUrls){
$userUrls->each(function($user) {
yield $this->client->requestAsync('GET', $user->pivot->url)
->then(function (ResponseInterface $response) use ($user) {
$this->dom->load((string)$response->getBody());
// ... some db stuff that inserts row in table for this
// $user with stuff from this request
});
});
});
$all = new EachPromise($promises, [
'concurrency' => 4,
'fulfilled' => function () {
},
]);
$all->promise()->wait();
回答1:
Not sure wht you don't get an error, but your generator is definitely wrong.
use Psr\Http\Message\ResponseInterface;
use function GuzzleHttp\Promise\each_limit_all;
$promises = function () use ($userUrls) {
foreach ($userUrls as $user) {
yield $this->client->getAsync($user->pivot->url)
->then(function (ResponseInterface $response) use ($user) {
$this->dom->load((string)$response->getBody());
// ... some db stuff that inserts row in table for this
// $user with stuff from this request
});
};
};
$all = each_limit_all($promises(), 4);
$all->promise()->wait();
Note foreach
instead of $userUrls->each()
, it's important because in your version generator function is the function that is passes to ->each()
call, not the one you assign to $promise
.
Also note that you must activate the generator (call $promises()
as pass the result, not pass the function itself to Guzzle).
Otherwise all looks good, try the code with my changes.
来源:https://stackoverflow.com/questions/55884007/guzzle-async-multiple-promises