HH\Asio\m

Translate a KeyedTraversable of Awaitables into a single Awaitable of Map`.

Description

function HH\Asio\m(
  KeyedTraversable<Tk,Awaitable<Tv>> $awaitables,
): Awaitable<Map<Tk,Tv>>

Translate a KeyedTraversable of Awaitables into a single Awaitable of Map`.

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 map 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 of KeyedTraversable awaitables.

Return Values

Examples

<?hh

namespace Hack\UserDocumentation\API\Examples\HH\Asio\m;

/**
 * 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);
}
Output
com: <!doctype html> ... </html>
net: <!doctype html> ... </html>
org: <!doctype html> ... </html>