-
|
Beta Was this translation helpful? Give feedback.
Answered by
dixyes
Jan 14, 2023
Replies: 2 comments 6 replies
-
defer个 |
Beta Was this translation helpful? Give feedback.
2 replies
Answer selected by
he426100
-
use Swow\Channel;
use Swow\Coroutine;
/**
* @param array $callbacks
* @param int $timeout 超时
* @param bool $throw 是否抛出异常
* @return mixed
*/
function promise_race(array $callbacks, int $timeout = -1, bool $throw = true): mixed
{
$coroutines = [];
try {
$channel = new Channel();
foreach ($callbacks as $callback) {
$coroutines[] = Coroutine::run(static function () use ($channel, $callback) {
$channel->push($callback());
});
}
$result = $channel->pop();
} catch (\Throwable $e) {
if ($throw) {
throw $e;
}
$result = false;
}
foreach ($coroutines as $coroutine) {
if ($coroutine->isExecuting()) {
$coroutine->kill();
}
}
return $result;
} $r = promise_race([
function () {
usleep(3_000);
echo "Never here 3\n";
return 3;
},
function () {
usleep(1_000);
echo "I am here 1\n";
return 1;
},
function () {
usleep(2_000);
echo "Never here 2\n";
return 2;
},
]);
var_dump($r);
好像不需要 Selector |
Beta Was this translation helpful? Give feedback.
4 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
defer个
Coroutine::run
来回收他们就行了