Await

For a definition of the word "await", see the Wiktionary entry await.

In computer programming, await is a feature found in C# 5.0, Python 3.5, in an experimental extension for Scala,[1] and more recently JavaScript that allows an asynchronous, non-blocking method call to be performed in a similar way to an ordinary synchronous method call.

While a casual reading of the code would suggest that the method call blocks until the requested data is available, in fact it does not.

In C#

This is an example:

    public async Task<int> SumPageSizesAsync(IList<Uri> uris) 
    {
        int total = 0;
        foreach (var uri in uris) {
            statusText.Text = string.Format("Found {0} bytes ...", total);
            var data = await new WebClient().DownloadDataTaskAsync(uri);
            total += data.Length;
        }
        statusText.Text = string.Format("Found {0} bytes total", total);
        return total;
    }

In Scala

In the experimental Scala-async extension to Scala, await is a "method", although it does not operate like an ordinary method. Furthermore, unlike in C# 5.0 in which a method must be marked as async, in Scala-async, a block of code is surrounded by an async "call".

How it works

In Scala-async, async is actually implemented using a Scala macro, which causes the compiler to emit different code, and produce a finite state machine implementation (which is considered to be more efficient than a monadic implementation, but less convenient to write by hand).

There are plans for Scala-async to support a variety of different implementations, including non-asynchronous ones.

In Python

Python 3.5 has added support for Async/Await as described in PEP0492 (https://www.python.org/dev/peps/pep-0492/).

In JavaScript

The initial spec for the ES7 (ES2016) feature can be found here: https://github.com/tc39/ecmascript-asyncawait.

Here's an example (modified from this[2] article):

async function createNewDoc() {
  let response = await db.post({}); // post a new doc
  return await db.get(response.id); // find by id
}

~async function main() {
  try {
    let doc = await createNewDoc();
    console.log(doc);
  } catch (err) {
    console.log(err);
  }
}()

See also

References

  1. "Scala Async". Retrieved 20 October 2013.
  2. "Taming the asynchronous beast with ES7". Retrieved 12 November 2015.


This article is issued from Wikipedia - version of the Monday, January 25, 2016. The text is available under the Creative Commons Attribution/Share Alike but additional terms may apply for the media files.