Guzzle Async Multiple Promises

会有一股神秘感。 提交于 2020-01-16 19:41:45

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!