idbeHoldL

amphp paralell tasks

Oct 21st, 2021
761
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <?php
  2.  
  3. use Amp\Deferred;
  4. use Amp\Loop;
  5. use function Amp\Promise\all;
  6. use function Amp\Promise\wait;
  7.      
  8. Loop::run(function () {
  9.  
  10.  
  11.     /**
  12.      * Какая-то асинхронная функция, возвращает Promise
  13.      */
  14.     $fnWait = function($num, $sec){
  15.         $deferred = new Deferred();
  16.  
  17.         Loop::delay($msDelay = $sec * 1000, function () use ($deferred, $num, $sec) {
  18.             $result = "resolve $num task for $sec seconds" . PHP_EOL;
  19.             echo $result;
  20.             $deferred->resolve($result);
  21.         });
  22.  
  23.         return $deferred->promise();
  24.     };
  25.  
  26.  
  27.     $arrArgs = [7,5,3,4,8];
  28.  
  29.     $promises = [];
  30.     foreach ($arrArgs as $num => $args){
  31.         $promises[] = $fnWait($num, $args);
  32.     }
  33.  
  34.     $results = wait(all($promises));
  35.  
  36.     var_dump($results);
  37.  
  38. });
  39.    
RAW Paste Data