簡體   English   中英

amphp:循環中的承諾

[英]amphp: Promises in Loops

對不起,伙計們,但我現在花了幾個小時有點發瘋,只是想不出哪里出了問題。

所以我有一個下載類,它需要將下載分成塊,然后請求每個塊作為一個單獨的請求,這一切都很好,我有點無處可去,我的承諾我的收益永遠不會返回任何東西,但也不會拋出任何錯誤。

它應該做的是遍歷分解的塊數組,然后對活動塊執行承諾,等待完成,然后繼續。

這是我在代碼庫中的測試:

/**
 * 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 手動分配任務來以不同的方式解決它,但這並不是最好的方法。

我將不勝感激,也許我只是看不到正在發生的事情或誤解了某些事情。

將 foreach 塊包裝在單獨的 asyncCall 中最終解決了這個問題。

暫無
暫無

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

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