ucscode/promise

PHP中轻量级的Promise实现

1.0.0 2024-01-22 16:12 UTC

This package is auto-updated.

Last update: 2024-09-22 17:35:49 UTC


README

Promise是JavaScript Promises在PHP中的简单、轻量级实现。Promise提供了一种干净且结构化的方式来处理异步操作,允许你处理延迟执行并更有效地管理异步工作流程。

特性

  • Promises/A+ 兼容:遵循Promises/A+规范以确保一致的行为。
  • 链式调用:使用then方法将Promise链式调用。
  • 错误处理:使用catch方法处理错误。
  • 最终化:使用finally方法执行无论Promise状态如何的代码。

入门指南

安装

composer require ucscode/promise

用法

use Ucscode\Promise\Promise;

$promise = new Promise(function ($resolve, $reject) {
    // Asynchronous operation
    sleep(20);
    $resolve("Operation Successful");
});

$promise->then(
    fn ($value) => "Fulfilled: $value",
    fn ($reason) => "Rejected: $reason"
)
->finally(fn () => "Operation complete");

多个Promise

Promise::all方法接受一个Promise数组,并收集它们的完成值。如果所有Promise都已完成,它将使用完成值数组解析。如果有任何Promise被拒绝,它将使用第一个拒绝Promise的原因拒绝。

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

Promise::all($promises)->then(
    function ($values) {
        // All promises fulfilled
        var_dump($values); // Output: array(1, 2, 3)
    },
    fn ($reason) => "At least one promise rejected"
);

贡献

欢迎贡献!请随意提交问题或拉取请求。

许可

本项目采用MIT许可