插件窝 干货文章 高效处理异步操作:Guzzle Promises 库的实践指南

高效处理异步操作:Guzzle Promises 库的实践指南

Promise Result function 异步 306    来源:    2025-03-12

Guzzle Promises 是一个用于处理异步操作的 PHP 库,它提供了一种简洁的方式来管理和组合异步任务。Guzzle Promises 的核心思想是通过 Promise 对象来表示异步操作的结果,并通过链式调用来处理这些结果。以下是如何高效使用 Guzzle Promises 库的实践指南。

1. 安装 Guzzle Promises

首先,你需要通过 Composer 安装 Guzzle Promises 库:

composer require guzzlehttp/promises

2. 基本用法

2.1 创建一个 Promise

你可以使用 GuzzleHttp\Promise\Promise 类来创建一个 Promise 对象。Promise 对象表示一个异步操作的结果,它可以是 pending(等待中)、fulfilled(已完成)或 rejected(已拒绝)。

use GuzzleHttp\Promise\Promise;

$promise = new Promise();
$promise->resolve('Hello, World!'); // 完成 Promise

2.2 处理 Promise 的结果

你可以通过 then 方法来处理 Promise 的结果。then 方法接受两个回调函数作为参数,第一个回调函数用于处理成功的结果,第二个回调函数用于处理失败的结果。

$promise->then(
    function ($value) {
        echo $value; // 输出: Hello, World!
    },
    function ($reason) {
        echo 'Failed: ' . $reason;
    }
);

3. 组合多个 Promise

Guzzle Promises 提供了多种方法来组合多个 Promise,例如 allsomeany 等。

3.1 使用 all 方法

all 方法会等待所有的 Promise 都完成,并返回一个包含所有结果的数组。

use GuzzleHttp\Promise\Promise;
use GuzzleHttp\Promise\Utils;

$promise1 = new Promise();
$promise2 = new Promise();

$promise1->resolve('Result 1');
$promise2->resolve('Result 2');

$allPromise = Utils::all([$promise1, $promise2]);

$allPromise->then(function ($results) {
    print_r($results); // 输出: ['Result 1', 'Result 2']
});

3.2 使用 some 方法

some 方法会等待指定数量的 Promise 完成,并返回这些 Promise 的结果。

use GuzzleHttp\Promise\Promise;
use GuzzleHttp\Promise\Utils;

$promise1 = new Promise();
$promise2 = new Promise();
$promise3 = new Promise();

$promise1->resolve('Result 1');
$promise2->resolve('Result 2');
$promise3->reject('Failed');

$somePromise = Utils::some(2, [$promise1, $promise2, $promise3]);

$somePromise->then(function ($results) {
    print_r($results); // 输出: ['Result 1', 'Result 2']
});

4. 错误处理

你可以使用 otherwise 方法来处理 Promise 的失败情况。

$promise->otherwise(function ($reason) {
    echo 'Failed: ' . $reason;
});

5. 链式调用

Guzzle Promises 支持链式调用,你可以在一个 then 方法中返回另一个 Promise,从而实现复杂的异步操作链。

$promise->then(function ($value) {
    return new Promise(function () use ($value) {
        return $value . ' and more';
    });
})->then(function ($value) {
    echo $value; // 输出: Hello, World! and more
});

6. 使用 wait 方法同步等待

如果你需要同步等待 Promise 的结果,可以使用 wait 方法。wait 方法会阻塞当前线程,直到 Promise 完成或失败。

$result = $promise->wait();
echo $result; // 输出: Hello, World!

7. 使用 settle 方法

settle 方法会等待所有的 Promise 完成(无论成功或失败),并返回一个包含所有结果的数组。

use GuzzleHttp\Promise\Promise;
use GuzzleHttp\Promise\Utils;

$promise1 = new Promise();
$promise2 = new Promise();

$promise1->resolve('Result 1');
$promise2->reject('Failed');

$settlePromise = Utils::settle([$promise1, $promise2]);

$settlePromise->then(function ($results) {
    print_r($results);
    // 输出:
    // [
    //     ['state' => 'fulfilled', 'value' => 'Result 1'],
    //     ['state' => 'rejected', 'reason' => 'Failed']
    // ]
});

8. 使用 each 方法

each 方法可以用于处理一个 Promise 数组,并对每个 Promise 的结果执行相同的操作。

use GuzzleHttp\Promise\Promise;
use GuzzleHttp\Promise\Utils;

$promises = [
    new Promise(function () { return 'Result 1'; }),
    new Promise(function () { return 'Result 2'; }),
    new Promise(function () { return 'Result 3'; }),
];

Utils::each($promises, function ($value) {
    echo $value . "\n";
})->wait();
// 输出:
// Result 1
// Result 2
// Result 3

9. 使用 coroutine 方法

Guzzle Promises 还支持使用协程(coroutine)来处理异步操作。协程可以让异步代码看起来像同步代码一样。

use GuzzleHttp\Promise\Promise;
use GuzzleHttp\Promise\Utils;

$promise = Utils::coroutine(function () {
    $result1 = yield new Promise(function () { return 'Result 1'; });
    $result2 = yield new Promise(function () { return 'Result 2'; });
    return $result1 . ' and ' . $result2;
});

$promise->then(function ($value) {
    echo $value; // 输出: Result 1 and Result 2
});

10. 总结

Guzzle Promises 提供了一种强大且灵活的方式来处理异步操作。通过使用 Promise 对象和链式调用,你可以轻松地管理和组合多个异步任务。此外,Guzzle Promises 还提供了多种工具方法来处理复杂的异步场景,如 allsomesettle 等。掌握这些工具和方法,可以让你在 PHP 中高效地处理异步操作。

希望这篇指南能帮助你更好地理解和使用 Guzzle Promises 库。如果你有任何问题或需要进一步的帮助,请随时提问!