labrador-kennel/composite-future

使用类型安全的 CompositeFuture 对象组合 Amp Futures 并按需等待。

1.3.0 2023-01-26 18:18 UTC

This package is auto-updated.

Last update: 2024-08-26 21:33:13 UTC


README

一个代表类型安全的 Amp\Future 对象集合,并提供对该集合进行操作的方法的对象。

安装

Composer 是安装 Labrador 包的唯一支持方法。

composer require labrador-kennel/composite-future

入门指南

此库提供的对象旨在提供一个类型,可以用于类型提示,在处理 Future 集合时提供更多信息。当使用 CompositeFuture 时,如果您提供了一个返回类型提示,您还可以构建类似处理单个 Future 的代码。始终,查看一些代码是开始的最佳方式!

<?php

namespace Acme\Demo;

use Amp\Future;
use Labrador\CompositeFuture\CompositeFuture;

function futuresGeneratingMethod() : CompositeFuture {
    $futures = ['a' => Future::complete(1), 'b' => Future::complete(2), 'c' => Future::error(new \Exception('something went wrong'))];
    return new CompositeFuture($futures);
}

$futures = futuresGeneratingMethod();
// Returns an array with keys equal to the index of the Future and the value to the Future resolution
// Will throw an exception when an error is encountered
$futures->await();

// Also has access to the following methods, which follow the same documentation as their corresponding
// Amp\Future functions.
$futures->awaitAll();
$futures->awaitAny();
$futures->awaitAnyN(2);
$futures->awaitFirst();

?>

动机

此库故意是一个非常简单的面向对象包装器,用于处理 Future 集合的实用函数。动机是为此类集合提供语义类型提示。在上面的示例中,如果没有 CompositeFuture,我们基本上有两种选择

  1. 在函数内部等待 Future;这可能不是最佳选择,因为每次调用可能需要以不同的方式处理等待。
  2. 从我们的方法返回一个数组;这可能不是最佳选择,因为它不如类型提示语义明确。

治理

所有 Labrador 包都遵守 Labrador Governance 仓库 中规定的规则。