当前位置: 首页 > 后端技术 > PHP

PHP实现Promise.all和Promise.race

时间:2023-03-29 16:15:22 PHP

测试$promise1=function(){msleep(500);返回“一”;};$promise2=function(){msleep(100);返回“二”;};$promise3=function(){msleep(50);thrownew\Exception('Reject');};var_dump(promise_all([$promise1,$promise2]));var_dump(promise_race([$promise1,$promise2]));var_dump(promise_race([$promise1,$promise2),$promise3]));结果#phppromise.phparray(2){[1]=>string(3)"two"[0]=>string(3)"one"}string(3)"two"object(例外)#15(7){}实现$callback){$wg->add();$通道->推送(真);Coroutine::run(staticfunction()使用($wg,$channel,$callback,$key,&$results){尝试{$results[$key]=$callback();}catch(\Throwable){}最后{$channel->pop();$wg->完成();}});}$wg->wait();return$results;}/***@paramarray$callbacks*@paramint$timeout超时*@parambool$throw是否抛出异常*@returnmixed*/functionpromise_race(array$callbacks,int$timeout=-1,bool$throw=true):混合{$coroutines=[];defer(staticfunction()use(&$coroutines){foreach($coroutinesas$coroutine){if($coroutine->isExecuting()){$coroutine->kill();}}});}$channel=newChannel();foreach($callbacksas$callback){$coroutines[]=Coroutines::run(staticfunction()use($channel,$callback){try{$channel->push($callback());}catch(\可抛出的$e){$channel->push($e);}});}try{return$channel->pop($timeout);}catch(\Throwable$e){if($throw){抛出$e;}}返回假;}