0

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

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

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

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

/**
 * 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 手动分配任务来解决它,但这并不是最好的方法。

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

4

1 回答 1

0

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

于 2021-11-01T02:39:18.107 回答