简体   繁体   English

amphp:循环中的承诺

[英]amphp: Promises in Loops

Sorry, guys, but I'm kinda getting crazy now spending Hours and just can't figure out what's wrong.对不起,伙计们,但我现在花了几个小时有点发疯,只是想不出哪里出了问题。

So I have a download class which needs to separate the download in chunks and then request each chunk as a separate request that's all fine where I'm kinda getting nowhere is my promises my yield never returns anything but also does not throw any error.所以我有一个下载类,它需要将下载分成块,然后请求每个块作为一个单独的请求,这一切都很好,我有点无处可去,我的承诺我的收益永远不会返回任何东西,但也不会抛出任何错误。

What it should do is go through the broken up chunk array then execute promises for the active chunks, wait for completion, then continue.它应该做的是遍历分解的块数组,然后对活动块执行承诺,等待完成,然后继续。

This is my test in the code base:这是我在代码库中的测试:

/**
 * 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);
        }

    
    }


}

I tried at least 20 variations, and it just won't work, the whole code runs in Loop::run我尝试了至少 20 个变体,但它不起作用,整个代码在 Loop::run 中运行

I know how to solve it differently by manually assigning tasks via Loop::repeat but that's not really the best way.我知道如何通过 Loop::repeat 手动分配任务来以不同的方式解决它,但这并不是最好的方法。

I would be grateful for help, perhaps I'm just loosing sight of what's going on or misunderstanding something.我将不胜感激,也许我只是看不到正在发生的事情或误解了某些事情。

将 foreach 块包装在单独的 asyncCall 中最终解决了这个问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM