组件Future::ignore

Future::ignore

(PHP 8.6+, True Async 1.0)

php
public function ignore(): Future

Future 标记为已忽略。如果 Future 以错误完成且该错误未被处理,它将不会被传递给事件循环的未处理异常处理器。适用于不关心结果的"发射后不管"任务。

返回值

Future — 返回同一个 Future,支持方法链式调用。

示例

示例 #1 忽略 Future 错误

php
<?php

use Async\Future;
use Async\FutureState;

// Launch a task whose errors we don't care about
$state  = new FutureState();
$future = new Future($state);
$future->ignore();

\Async\spawn(function() use ($state) {
    // This operation may fail
    try {
        sendAnalytics(['event' => 'page_view']);
        $state->complete(null);
    } catch (\Throwable $e) {
        $state->error($e);
    }
});

// The error will not be passed to the event loop handler

示例 #2 在方法链中使用 ignore

php
<?php

use Async\Future;
use Async\FutureState;

function warmupCache(array $keys): void {
    foreach ($keys as $key) {
        $state = new FutureState();
        (new Future($state))->ignore();  // Cache errors are not critical

        \Async\spawn(function() use ($state, $key) {
            try {
                $data = loadFromDatabase($key);
                saveToCache($key, $data);
                $state->complete(null);
            } catch (\Throwable $e) {
                $state->error($e);
            }
        });
    }
}

warmupCache(['user:1', 'user:2', 'user:3']);

参见