Amphp之Promise组合器

本文介绍Amp异步库中的Promise组合器all()、some()、any()及first()的功能与用法。这些组合器能高效地管理并执行多个异步任务,尤其适用于并发场景。

Amp之Promise组合器

多个 Promise 可以使用不同的函数组合成一个 Promise。

all()

Amp\Promise\all()将一组 Promise 对象组合成一个 Promise,当该组中的所有 Promise 解决时,该 Promise 将解决。如果任何一个 Amp\Promise 实例失败,则组合器的 Promise 将失败。否则,生成的 Promise 将通过一个数组将输入数组中的键与其解析值匹配成功。

all()组合器非常强大,因为它允许我们同时执行许多异步操作。让我们看一个使用 Amp HTTP 客户端 (Artax) 并发检索多个 HTTP 资源的简单示例:

<?php

use Amp\Loop;
use Amp\Promise;

Loop::run(function () {
    $httpClient = new Amp\Artax\DefaultClient;
    $uris = [
        "google" => "http://www.google.com",
        "news"   => "http://news.google.com",
        "bing"   => "http://www.bing.com",
        "yahoo"  => "https://www.yahoo.com",
    ];

    try {
        // magic combinator sauce to flatten the promise
        // array into a single promise.
        // yielding an array is an implicit "yield Amp\Promise\all($array)".
        $responses = yield array_map(function ($uri) use ($httpClient) {
            return $httpClient->request($uri);
        }, $uris);

        foreach ($responses as $key => $response) {
            printf(
                "%s | HTTP/%s %d %s\n",
                $key,
                $response->getProtocolVersion(),
                $response->getStatus(),
                $response->getReason()
            );
        }
    } catch (Amp\MultiReasonException $e) {
        // If any one of the requests fails the combo will fail and
        // be thrown back into our generator.
        echo $e->getMessage(), "\n";
    }

    Loop::stop();
});

some()

Amp\Promise\some()与 all() 相同,只是它可以容忍个别故障。只要传递的promise中至少有一个成功,合并的promise就会成功。成功的解析值是 [$arrayOfErrors, $arrayOfValues] 形式的数组。组件数组中的各个键从传递给仿函数进行评估的承诺数组中保留下来。

any()

Amp\Promise\any()与 some() 相同,只是它容忍所有失败。即使所有的承诺都失败了,它也会成功。

first()

Amp\Promise\first()以第一个成功结果解析。仅当组中的所有 Promise 都失败或 Promise 数组为空时,生成的 Promise 才会失败。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值