Guzzle 异步多重承诺

Guzzle Async Multiple Promises

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

而且我确信没有任何事情发生,因为数据库中没有插入任何内容。有什么想法我想念的吗? (我用各自的 then 产生每个请求,因为在每个承诺结束时,数据库操作特定于该用户)

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

不确定你没有得到错误,但你的生成器肯定是错误的。

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() 调用的函数,而不是您分配给 [=14 的函数=].

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

否则一切看起来都不错,试试我更改过的代码。