HH\Asio\m

Translate a KeyedTraversable of Awaitables into a single AwaitableofMap`

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 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

Returns

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);
}

<<__EntryPoint>>
async function basic_usage_main(): Awaitable<void> {
  $urls = ImmMap {
    'com' => "http://example.com",
    'net' => "http://example.net",
    'org' => "http://example.org",
  };

  $pages = await get_urls($urls);
  foreach ($pages as $name => $page) {
    echo $name.': ';
    echo \substr($page, 0, 15).' ... '.\substr($page, -8);
  }
}
```.skipif
// Skip if we don't have an internet connection
if (!\get_headers("www.example.com")) {
  print "skip";
}