Skip to content

Commit

Permalink
temporaly add Promise::all
Browse files Browse the repository at this point in the history
code came from #6015 and will be subject to probable changes
  • Loading branch information
ShockedPlot7560 committed Oct 14, 2023
1 parent 538b698 commit 5fe57a8
Showing 1 changed file with 52 additions and 1 deletion.
53 changes: 52 additions & 1 deletion src/promise/Promise.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,11 @@

namespace pocketmine\promise;

use function count;
use function spl_object_id;

/**
* @phpstan-template TValue
* @phpstan-template-covariant TValue
*/
final class Promise{
/**
Expand All @@ -52,4 +53,54 @@ public function onCompletion(\Closure $onSuccess, \Closure $onFailure) : void{
public function isResolved() : bool{
return $this->shared->resolved;
}

/**
* Returns a promise that will resolve only once all the Promises in
* `$promises` have resolved. The resolution value of the returned promise
* will be an array containing the resolution values of each Promises in
* `$promises` indexed by the respective Promises' array keys.
*
* @template TPromiseValue
* @phpstan-param Promise<TPromiseValue>[] $promises
*
* @phpstan-return Promise<array<int, TPromiseValue>>
*/
public static function all(array $promises) : Promise {
/** @phpstan-var PromiseResolver<array<int, TPromiseValue>> $resolver */
$resolver = new PromiseResolver();
$values = [];
$toResolve = count($promises);
$continue = true;

foreach($promises as $key => $promise){
$values[$key] = null;

$promise->onCompletion(
function(mixed $value) use ($resolver, $key, &$toResolve, &$continue, &$values) : void{
$values[$key] = $value;

if(--$toResolve === 0 && $continue){
$resolver->resolve($values);
}
},
function() use ($resolver, &$continue) : void{
if($continue){
$continue = false;
$resolver->reject();
}
}
);

if(!$continue){
break;
}
}

if($toResolve === 0){
$continue = false;
$resolver->resolve($values);
}

return $resolver->getPromise();
}
}

0 comments on commit 5fe57a8

Please sign in to comment.