onion/promise

1.0.0 2019-01-21 00:17 UTC

README

Build Status Mutation testing badge

这是一个完全兼容任何现有实现,且不依赖任何第三方库的 Promises/A+ 实现。

此包定义了2个接口 PromiseInterface & ThenableInterface,根据规范还提供了一些辅助函数和一些使代码更简洁的函数。

is_thenable - 检查一个对象是否是 "thenable" 的函数 coroutine - 将任务作为承诺推送。这个函数的实现会根据服务器上是否安装了 swoole 扩展而改变。如果安装了,则使用作为 go 函数提供的本地协程,否则退回到类似事件循环的方法。

使用 register_tick_function 注册了一个定时器函数,它会每执行一个任务,以避免在执行时完全停止应用程序。此外,还注册了一个关闭函数,它会以阻塞方式运行所有剩余的任务,直到队列清空,尽管这会导致请求挂起。

当使用同步模式时,你应该做 declare(ticks=1),参见 PHP 文档

注意:请记住,你的代码将在任务处理完毕之前阻塞,因此这种 '模式' 不推荐使用,并且用户应该寻找其他方法来处理他们的重任务或安装 swoole

async - coroutine 的别名,旨在模仿 JS/TS/C# 中的 async 关键字

==============

使用方法

use \Onion\Framework\Promise\async;

$promise = async(function () use ($orm, $id, $password) {
    $user = $orm->findById($id); // if it throws any exception the promise will immediately get rejected

    if (!$user->isActive()) {
        throw new \RuntimeException('User is not activated yet');
    }

    if (!password_verify($password, $user->getPassword())) {
        throw new \InvalidArgumentException('Invalid password provided');
    }

    return $user;
})->then(function (User $user) use ($paymentService) {
    $paymentService->processUserPayment($user->getId());
    echo "User {$user->getId()} processed successfully";
}, function (\Throwable $ex) {
    echo "Ops.. {$ex->getMessage()}";
})->otherwise(function (\Throwable $ex) {
    // Do something else with the exception maybe ?
})->finally(function () use ($orm) {
    // Regardless of the state change, but it is always called at the end of execution
    $orm->disconnect();
});

传递给 async/coroutine 的函数将立即执行,所以请注意,在使用时如果没有 swoole