컴포넌트Future::failed

Future::failed

(PHP 8.6+, True Async 1.0)

php
public static function failed(\Throwable $throwable): Future

지정된 오류로 즉시 완료된 Future를 생성합니다. 이러한 Future에 await()를 호출하면 제공된 예외가 발생합니다.

매개변수

throwable — Future가 완료될 예외.

반환값

Future — 오류로 완료된 Future.

예제

예제 #1 오류를 가진 Future 생성

php
<?php

use Async\Future;
use Async\FutureState;

$future = Future::failed(new \RuntimeException("Loading error"));

var_dump($future->isCompleted()); // bool(true)

try {
    $future->await();
} catch (\RuntimeException $e) {
    echo "Caught: " . $e->getMessage() . "\n";
    // Caught: Loading error
}

예제 #2 조기 오류 반환에 사용

php
<?php

use Async\Future;
use Async\FutureState;

function connectToService(string $host): Future {
    if (empty($host)) {
        return Future::failed(
            new \InvalidArgumentException("Host cannot be empty")
        );
    }

    $state = new FutureState();

    \Async\spawn(function() use ($state, $host) {
        try {
            $state->complete(performConnection($host));
        } catch (\Throwable $e) {
            $state->error($e);
        }
    });

    return new Future($state);
}

$future = connectToService('');
$future
    ->catch(function(\Throwable $e) {
        echo "Error: " . $e->getMessage() . "\n";
    })
    ->ignore();

같이 보기