1
0
mirror of https://github.com/danog/amp.git synced 2024-12-12 09:29:45 +01:00
amp/docs/futures/combinators.md

68 lines
2.2 KiB
Markdown
Raw Normal View History

---
2021-12-03 00:09:53 +01:00
layout: "docs"
2021-12-03 00:32:48 +01:00
title: "Future Combinators"
permalink: "/futures/combinators"
---
2021-12-03 00:50:46 +01:00
Amp provides a set of helper functions to deal with multiple futures and combining them.
## `all()`
2021-12-03 00:50:46 +01:00
`Amp\Future\all()` awaits all `Future` objects of an `iterable`. If one of the `Future` instances errors, the operation
will be aborted with that exception. Otherwise, the result is an array matching keys from the input `iterable` to their
resolved values.
2021-12-03 00:09:53 +01:00
The `all()` combinator is extremely powerful because it allows us to concurrently execute many asynchronous operations
2021-12-03 00:50:46 +01:00
at the same time. Let's look at a simple example using [`amphp/http-client`](https://github.com/amphp/http-client) to
retrieve multiple HTTP resources concurrently:
```php
<?php
2021-12-03 00:50:46 +01:00
use Amp\Future;
$httpClient = HttpClientBuilder::buildDefault();
$uris = [
"google" => "https://www.google.com",
"news" => "https://news.google.com",
"bing" => "https://www.bing.com",
"yahoo" => "https://www.yahoo.com",
];
2021-12-03 00:50:46 +01:00
try {
$responses = Future\all(array_map(function ($uri) use ($httpClient) {
return $httpClient->request(new Request($uri, 'HEAD'));
}, $uris));
foreach ($responses as $key => $response) {
printf(
"%s | HTTP/%s %d %s\n",
$key,
$response->getProtocolVersion(),
$response->getStatus(),
$response->getReason()
);
}
} catch (Amp\CompositeException $e) {
// If any one of the requests fails the combo will fail
echo $e->getMessage(), "\n";
}
```
2017-12-06 12:36:51 +01:00
## `some()`
2021-12-03 00:50:46 +01:00
`Amp\Future\some()` is the same as `all()` except that it tolerates individual failures. A result is returned once
exactly `$count` instances in the `iterable` complete successfully. The return value is an array of values. The
individual keys in the component array are preserved from the `iterable` passed to the function for evaluation.
2021-12-03 00:50:46 +01:00
## `settle()`
`Amp\Promise\settle()` awaits all futures and returns their results as `[$errors, $values]` array.
2021-12-03 00:50:46 +01:00
## `race()`
2021-12-03 00:50:46 +01:00
`Amp\Promise\race()` unwraps the first completed `Future`, whether successfully completed or errored.
## `any()`
2021-12-03 00:50:46 +01:00
`Amp\Promise\any()` unwraps the first successfully completed `Future`.