【问题标题】:Guzzle Async Multiple PromisesGuzzle 异步多个 Promise
【发布时间】:2019-09-16 22:27:24
【问题描述】:

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

而且我确信没有任何事情发生,因为数据库中没有插入任何内容。有什么我想念的想法吗? (我使用其各自的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();

【问题讨论】:

    标签: php guzzle guzzle6


    【解决方案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)。

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

    【讨论】:

      猜你喜欢
      • 2016-11-11
      • 1970-01-01
      • 2020-02-18
      • 2016-10-06
      • 2022-11-28
      • 2017-01-15
      • 2021-07-09
      • 2017-07-09
      • 1970-01-01
      相关资源
      最近更新 更多