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 才会失败。