【问题标题】:Uncaught Error: Class "GuzzleHttp\Promise\EachPromise"未捕获的错误:类“GuzzleHttp\Promise\EachPromise”
【发布时间】:2021-08-13 16:19:01
【问题描述】:

我尝试实现以下代码,但它显示EachPromise Error class not foundPromise Error class not found。 Guzzle 库已安装。然后也出现了这个错误。

<?php

use GuzzleHttp\Promise\EachPromise;
use GuzzleHttp\Psr7\Response;

$users = ['one', 'two', 'three'];

$promises = (function () use ($users) {
    foreach ($users as $user) {
        
        // Using generator
        yield $this->getAsync(
'https://api.demo.com/v1/users?username='
        . $user);       
    }
})();

$eachPromise = new EachPromise($promises, [
    
    // Number of concurrency
    'concurrency' => 4,
    'fulfilled' => function (Response $response) {
        if ($response->getStatusCode() == 200) {
            $user = json_decode(
                $response->getBody(), true);
            
            // processing response of the user
        }
    },
    
    'rejected' => function ($reason) {
    // handle promise rejected
    }
]);
$eachPromise->promise()->wait();
?>

【问题讨论】:

    标签: php cron backend guzzle


    【解决方案1】:

    似乎没有自动加载器可以定位和加载代码中提到的类文件。

    如果你的 Guzzle 包是用 composer 安装的,你可以试试你的源码根目录下的 require_once() /vendor/autoloader.php 文件。

    否则,请尝试单独加载这些类文件 - 现代 PHP 世界不建议这样做(尽可能使用自动加载器)。

    require_once("path-to/EachPromise.php");
    require_once("path-to/Response.php");
    

    编辑

    再看一遍,您的代码使用了$this,它需要一个对象实例上下文,其中$this-&gt;getAsync() 可用,但显然不是这样。该代码看起来像是从 Class 对象中部分复制粘贴的代码片段,不会在您的给定设置中运行。

    您可能需要设置示例代码的代码上下文。

    【讨论】:

    • 添加 require_once 文件后,遇到这个错误 Uncaught Error: Call to undefined function EachPromise() For this code $eachPromise = new EachPromise($promises, [ // Number of concurrency 'concurrency' =&gt; 4, 'fulfilled' =&gt; function (Response $response) { if ($response-&gt;getStatusCode() == 200) { $user = json_decode( $response-&gt;getBody(), true); // processing response of the user } }, 'rejected' =&gt; function ($reason) { // handle promise rejected } ]);
    • 有没有办法实现这个特定的代码
    猜你喜欢
    • 2019-01-23
    • 2021-02-20
    • 1970-01-01
    • 2021-02-06
    • 2019-08-04
    • 2019-04-04
    • 1970-01-01
    • 1970-01-01
    • 2017-07-24
    相关资源
    最近更新 更多