Guzzle Async Multiple Promises

问题描述 投票:0回答:1

所以我试图使用guzzle来处理几个并发请求。我在网上看过几个例子,这就是我想出来的,但似乎无法让它发挥作用。没有错误,没有警告,没有。我已经尝试记录每个承诺但没有任何反应。

我确信没有任何事情发生,因为没有任何东西插入数据库。我缺少什么想法? (我正在使用各自的then产生每个请求,因为在每个promise的末尾,DB操作特定于该用户)

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();
php guzzle guzzle6
1个回答
1
投票

不确定你没有得到错误,但你的发电机肯定是错的。

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();

注意foreach而不是$userUrls->each(),这很重要,因为在你的版本生成器函数中是传递给->each()调用的函数,而不是你分配给$promise的函数。

另请注意,您必须激活生成器(调用$promises()作为传递结果,而不是将函数本身传递给Guzzle)。

否则一切看起来都不错,请尝试使用我的更改代码。

© www.soinside.com 2019 - 2024. All rights reserved.