HH\Asio\m
Translate a KeyedTraversable
of Awaitables
into a single Awaitable of
Map`
namespace HH\Asio;
function m<Tk as arraykey, Tv>(
KeyedTraversable<Tk, Awaitable<Tv>> $awaitables,
): Awaitable<Map<Tk, Tv>>;
This function takes any KeyedTraversable
object of Awaitables
(i.e.,
each member of the KeyedTraversable
has a value of type of Awaitable
,
likely from a call to a function that returned Awaitable<T>
), and
transforms those Awaitables
into one big Awaitable
Map
.
This function is called m
because we are returning a m
ap of Awaitable
.
Only When you await
or join
the resulting Awaitable
, will all of the
key/values in the Map
within the returned Awaitable
be available.
Parameters
KeyedTraversable<Tk, Awaitable<Tv>> $awaitables
- The collection ofKeyedTraversable
awaitables.
Returns
Awaitable<Map<Tk, Tv>>
- AnAwaitable
ofMap
, where theMap
was generated from eachKeyedTraversable
member in$awaitables
.
Examples
/**
* Query an arbitrary number of URLs in parallel
* returning them as a Map of string responses.
*/
async function get_urls(
\ConstMap<string, string> $urls,
): Awaitable<Map<string, string>> {
// Wrap each URL string into a curl_exec awaitable
$handles = $urls->map($url ==> \HH\Asio\curl_exec($url));
// Wait on each handle in parallel and return the results
return await \HH\Asio\m($handles);
}
$urls = ImmMap {
'com' => "http://example.com",
'net' => "http://example.net",
'org' => "http://example.org",
};
$pages = \HH\Asio\join(get_urls($urls));
foreach ($pages as $name => $page) {
echo $name.': ';
echo substr($page, 0, 15).' ... '.substr($page, -8);
}
com: <!doctype html> ... </html>
net: <!doctype html> ... </html>
org: <!doctype html> ... </html>