Skip to content

Instantly share code, notes, and snippets.

@leonerd
Created July 30, 2019 17:42
Show Gist options
  • Save leonerd/6706590e1428c265c6cde54d0a5a4986 to your computer and use it in GitHub Desktop.
Save leonerd/6706590e1428c265c6cde54d0a5a4986 to your computer and use it in GitHub Desktop.

ECMAScript6 allows programmers to write programs in an asynchronous style, in order to achieve higher performance through concurrency. Such features as the async/await syntax mean that asynchronous functions can be written in a natural way that reads similar to straight-line code. The function can be suspended midway through execution until a result arrives that allows it to continue.

Here is an example which shows how you can use this syntax to implement a function that suspends in the middle of execution until it has received a response to the HTTP request we sent.

const fetch = require("node-fetch");

async function getJson(url) {
  try {
    const response = await fetch(url);
    const json = await response.json();
    return json;
  } catch (error) {
    console.log(error);
  }
}

We can write a similar thing in Perl 5. In ECMAScript6 the event system is built into the language, whereas in Perl 5 we get to choose our own. Because of this, the example is a little more verbose because it has to specify more of these choices.

use Future::AsyncAwait;

use IO::Async::Loop;
use Net::Async::HTTP;

my $loop = IO::Async::Loop->new;

my $http = Net::Async::HTTP->new;
$loop->add( $http );

async sub get_json($url)
{
  try {
    my $response = await $http->GET( $url );
    return decode_json( $response->decoded_content );
  }
  catch {
    warn "Failed to get JSON: $@\n";
  }
}

In both languages we see the await keyword causes the function to wait until the result of its sub-expression is ready. The argument to the await keyword is a value of a type that wraps up the idea of "an operation that may still be pending". In ECMAScript6 that is a value of Promise type; in Perl 5 it is a Future. These are two different names for what is essentially the same idea - in both cases the value encapsulates the concept of an operation that is still ongoing, and will yield its result later. The await keyword is used to suspend the currently-running function until that result is available.

Similarly, in both languages the async keyword decorates a function declaration and remarks that it may return its own result asynchronously via one of these deferred-result values (a Promise or Future), and allows that function to make use of the await expression.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment