【问题标题】:amphp: Promises in Loopsamphp:循环中的承诺
【发布时间】:2021-12-15 20:45:39
【问题描述】:

对不起,伙计们,但我现在花了几个小时有点发疯了,只是不知道出了什么问题。

所以我有一个下载类,它需要将下载分成多个块,然后将每个块作为一个单独的请求来请求,这一切都很好,我有点无处可去,我的承诺是我的收益永远不会返回任何东西,但也不会抛出任何东西错误。

它应该做的是遍历分解的块数组,然后为活动块执行承诺,等待完成,然后继续。

这是我在代码库中的测试:

/**
 * Start Download
 * 
 * @return void
 */
private function download() {


    $app = $this->app;
    $_this = $this;

    $chunks = array();
    for ($i=0; $i < $this->chunkCount+20; $i++) { 

        $start = $i * $this->chunkSize;
        $end = ($i+1)*$this->chunkSize;

        if($i == $this->chunkCount-1) {
            $end = $this->size;
        }

        $chunks[] = (object) ['id' => ($i+1), 'start'=>$start , 'end'=>$end, $path = $this->path."/".$i];

    }

    $chunkedChunks = array_chunk($chunks, $this->connections);

    foreach($chunkedChunks as $key => $chunkedChunk) {

        $urls = [
            'https://secure.php.net',
            'https://amphp.org',
            'https://github.com',           
        ];

        $promises = [];
        foreach ($urls as $url) {
            $promises[$url] = \Amp\call(function() use ($url) {
                $deferred = new \Amp\Deferred();

                \Amp\Loop::delay(3 * 1000, function () use ($url, $deferred) {
                    $deferred->resolve($url);
                });

                return $deferred->promise();
            });
        }

        $responses = yield \Amp\Promise\all($promises);

        foreach ($responses as $url => $response) {
            \printf("Read %d bytes from %s\n", \strlen($response), $url);
        }

    
    }


}

我尝试了至少 20 种变体,但都行不通,整个代码在 Loop::run 中运行

我知道如何通过 Loop::repeat 手动分配任务来解决这个问题,但这并不是最好的方法。

我会很感激您的帮助,也许我只是对正在发生的事情视而不见或误解了某些事情。

【问题讨论】:

    标签: php yield amphp


    【解决方案1】:

    将 foreach 块包装在单独的 asyncCall 中最终解决了它。

    【讨论】:

      猜你喜欢
      • 2018-03-25
      • 2018-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-17
      • 2016-10-11
      • 2019-01-23
      相关资源
      最近更新 更多