簡體   English   中英

食人魚異步多個承諾

[英]Guzzle Async Multiple Promises

因此,我正在嘗試將guzzle用於幾個並發請求。 我在網上看到了幾個示例,這是我想出的,但似乎無法使其正常工作。 沒有錯誤,沒有警告,什么都沒有。 我已經嘗試在每個諾言中登錄,但沒有任何反應。

而且我肯定知道什么都不會發生,因為什么都沒有插入數據庫中。 有什么想法我想念的嗎? (我得到與其相應的每一個請求then ,因為在每一個承諾的結束時,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();

不知道您沒有收到錯誤,但是您的生成器肯定是錯誤的。

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)。

否則,一切看起來都不錯,請嘗試用我的更改編寫代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM