HH\Asio\vmk

Returns an Awaitable of Vector after a mapping operation has been applied to each key and value in the provided KeyedTraversable.

Description

function HH\Asio\vmk(
  KeyedTraversable<Tk,Tv> $inputs,
  HH\Asio\(function(Tk,Tv):Awaitable<Tr>) $callable,
): Awaitable<Vector<Tr>>

Returns an Awaitable of Vector after a mapping operation has been applied to each key and value in the provided KeyedTraversable.

This function is similar to vm(), but passes element keys to the callable as well.

This function is similar to Vector::mapWithKey(), but the mapping of the keys and values is done using Awaitables.

This function is called vmk because we are returning a vector and doing a mapping operation that includes keys.

$callable must return an Awaitable.

The values in the Vector of the returned Awaitable are not available until you await or join the returned Awaitable.

Parameters

  • KeyedTraversable<Tk,Tv> $inputs - The KeyedTraversable of keys and values to map.
  • HH\Asio\(function(Tk,Tv):Awaitable<Tr>) $callable - The callable containing the Awaitable operation to apply to $inputs.

Return Values

Examples

<?hh

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

/**
 * Query an arbitrary number of URLs in parallel
 * returning them as a Vector of string responses.
 */
async function get_urls(
  \ConstVector<string> $urls,
): Awaitable<Vector<string>> {

  // Await on curl requests in parallel and
  // prepend the request ID index
  return await \HH\Asio\vmk(
    $urls,
    async ($idx, $url) ==> {
      $content = await \HH\Asio\curl_exec($url);
      return $idx . " => " . $content;
    },
  );
}

$urls = ImmVector {
  "http://example.com",
  "http://example.net",
  "http://example.org",
};

$pages = \HH\Asio\join(get_urls($urls));
foreach ($pages as $page) {
  echo substr($page, 0, 20) . ' ... ' . substr($page, -8);
}
Output
0 => <!doctype html> ... </html>
1 => <!doctype html> ... </html>
2 => <!doctype html> ... </html>