食人鱼异步多个承诺 [英] Guzzle Async Multiple Promises

查看:76
本文介绍了食人鱼异步多个承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我正在尝试将guzzle用于几个并发请求.我在网上看到了几个示例,这是我想出的,但似乎无法使其正常工作.没有错误,没有警告,什么都没有.我已经尝试在每个诺言中登录,但是什么也没有发生.

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.

我肯定知道什么都没发生,因为没有任何东西插入数据库.有什么想法我想念的吗?(我在生成每个请求时都带有各自的 then ,因为在每个承诺结束时,数据库操作都是针对该用户的)

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

推荐答案

不确定是否没有错误,但是生成器肯定是错误的.

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

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

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.

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

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.

这篇关于食人鱼异步多个承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆