Future::await

(PHP 8.6+, True Async 1.0)

public function await(?Completable $cancellation = null): mixed

等待 Future 完成并返回其结果。阻塞当前协程直到 Future 完成。如果 Future 以错误完成,该方法将抛出该异常。可以传入一个 Completable 对象,通过超时或外部条件来取消等待。

参数

cancellation — 等待取消对象。如果提供了该参数并且在 Future 完成之前被触发,将抛出 CancelledException。默认为 null

返回值

mixed — Future 的结果。

错误

如果 Future 以错误完成或被取消,将抛出异常。

示例

示例 #1 基本的结果等待

<?php

use Async\Future;

$future = \Async\async(function() {
    \Async\delay(100);
    return 42;
});

$result = $future->await();
echo "Result: $result\n"; // Result: 42

示例 #2 等待时处理错误

<?php

use Async\Future;

$future = \Async\async(function() {
    throw new \RuntimeException("Something went wrong");
});

try {
    $result = $future->await();
} catch (\RuntimeException $e) {
    echo "Error: " . $e->getMessage() . "\n";
    // Error: Something went wrong
}

参见