Questions tagged [async-await]

This covers the asynchronous programming model supported by various programming languages, using the async and await keywords.

Several programming languages support an asynchronous programming model using co-routines, with the async and await keywords.

Support for the model was added to

  • C# and VB in VS2012
  • Python in 3.5
  • ECMAScript in ECMAScript 2017
  • Rust in 1.39

C# and Visual Studio

Asynchronous programming with async and await was introduced with C# 5.0 in Visual Studio 2012. The run-time support for this language concept is a part of .NET 4.5 / Windows Phone 8 / Windows 8.x Store Runtime.

It's also possible to use async/await and target .NET 4.0 / Windows Phone 7.1 / Silverlight 4 / MonoTouch / MonoDroid / Portable Class Libraries, with Visual Studio 2012+ and Microsoft.Bcl.Async NuGet package, which is licensed for production code.

Async CTP add-on for VS2010 SP1 is also available, but it is not suitable for product development.

Python

Similar syntax was introduced to Python 3.5 (see PEP 492 - Coroutines with async and await syntax.

Previously, it was possible to write co-routines using generators; with the introduction of await and async co-routines were lifted to a native language feature.

ECMAScript

The async and await keywords were first reserved in the ECMAScript 2016 specification and then their use and behavior was fully-specified in the ECMAScript 2017 specification.

Examples

Take the following example, first written using Promises. This code chains a set of animations on an element, stopping when there is an exception in animation, and returning the value produced by the final successfully executed animation.

function chainAnimationsPromise(elem, animations) {
    var ret = null;
    var p = currentPromise;
    for (var anim in animations) {
        p = p.then(function(val) {
            ret = val;
            return anim(elem);
        })
    }
    return p.catch(function(e) {
        /* ignore and keep going */
    }).then(function() {
        return ret;
    });
}

Already with promises, the code is much improved from a straight callback style, where this sort of looping and exception handling is challenging.

Task.js and similar libraries offer a way to use generators to further simplify the code maintaining the same meaning:

function chainAnimationsGenerator(elem, animations) {
    return spawn(function*() {
        var ret = null;
        try {
            for(var anim of animations) {
                ret = yield anim(elem);
            }
        } catch(e) { /* ignore and keep going */ }
        return ret;
    });
}

This is a marked improvement. All of the promise boilerplate above and beyond the semantic content of the code is removed, and the body of the inner function represents user intent. However, there is an outer layer of boilerplate to wrap the code in an additional generator function and pass it to a library to convert to a promise. This layer needs to be repeated in every function that uses this mechanism to produce a promise. This is so common in typical async Javascript code, that there is value in removing the need for the remaining boilerplate.

With async functions, all the remaining boilerplate is removed, leaving only the semantically meaningful code in the program text:

async function chainAnimationsAsync(elem, animations) {
    var ret = null;
    try {
        for(var anim of animations) {
            ret = await anim(elem);
        }
    } catch(e) { /* ignore and keep going */ }
    return ret;
}

This is morally similar to generators, which are a function form that produces a Generator object. This new async function form produces a Promise object.

Trivia

Asynchrony doesn't assume multithreading, async or await keywords do not magically create any threads.

Resources:

C#

Related:

20260 questions
1750
votes
26 answers

Using async/await with a forEach loop

Are there any issues with using async/await in a forEach loop? I'm trying to loop through an array of files and await on the contents of each file. import fs from 'fs-promise' async function printFiles () { const files = await getFilePaths() //…
Saad
  • 32,434
  • 19
  • 55
  • 98
1186
votes
25 answers

How and when to use ‘async’ and ‘await’

From my understanding one of the main things that async and await do is to make code easy to write and read - but is using them equal to spawning background threads to perform long duration logic? I'm currently trying out the most basic example.…
Dan Dinu
  • 28,044
  • 21
  • 67
  • 100
1031
votes
15 answers

How to call asynchronous method from synchronous method in C#?

I have a public async void Foo() method that I want to call from synchronous method. So far all I have seen from MSDN documentation is calling async methods via async methods, but my whole program is not built with async methods. Is this even…
Tower
  • 87,855
  • 117
  • 329
  • 496
681
votes
25 answers

How would I run an async Task method synchronously?

I'm learning about async/await, and ran into a situation where I need to call an async method synchronously. How can I do that? Async method: public async Task GetCustomers() { return await Service.GetCustomersAsync(); } Normal…
Rachel
  • 122,023
  • 59
  • 287
  • 465
653
votes
8 answers

Syntax for an async arrow function

I can mark a JavaScript function as "async" (i.e., returning a promise) with the async keyword. Like this: async function foo() { // Do something } What is the equivalent syntax for arrow functions?
BonsaiOak
  • 20,455
  • 5
  • 25
  • 50
611
votes
4 answers

Best practice to call ConfigureAwait for all server-side code

When you have server-side code (i.e. some ApiController) and your functions are asynchronous - so they return Task - is it considered best practice that any time you await functions that you call ConfigureAwait(false)? I had read that it…
Arash Emami
  • 6,767
  • 3
  • 18
  • 20
512
votes
23 answers

How can I wait In Node.js (JavaScript)? l need to pause for a period of time

I'm developing a console script for personal needs. I need to be able to pause for an extended amount of time, but, from my research, Node.js has no way to stop as required. It’s getting hard to read users’ information after a period of time... I’ve…
Christopher Allen
  • 5,578
  • 4
  • 17
  • 31
481
votes
9 answers

If my interface must return Task what is the best way to have a no-operation implementation?

In the code below, due to the interface, the class LazyBar must return a task from its method (and for argument's sake can't be changed). If LazyBars implementation is unusual in that it happens to run quickly and synchronously - what is the best…
Jon Rea
  • 8,539
  • 3
  • 26
  • 33
450
votes
6 answers

Using async/await for multiple tasks

I'm using an API client that is completely asynchrounous, that is, each operation either returns Task or Task, e.g: static async Task DoSomething(int siteId, int postId, IBlogClient client) { await client.DeletePost(siteId, postId); // call…
Ben Foster
  • 32,767
  • 35
  • 157
  • 274
428
votes
13 answers

Combination of async function + await + setTimeout

I am trying to use the new async features and I hope solving my problem will help others in the future. This is my code which is working: async function asyncGenerator() { // other code while (goOn) { // other code var fileList…
JShinigami
  • 4,503
  • 3
  • 9
  • 15
402
votes
8 answers

Why can't I use the 'await' operator within the body of a lock statement?

The await keyword in C# (.NET Async CTP) is not allowed from within a lock statement. From MSDN: An await expression cannot be used in a synchronous function, in a query expression, in the catch or finally block of an exception handling …
Kevin
  • 7,234
  • 4
  • 25
  • 30
400
votes
7 answers

Is Task.Result the same as .GetAwaiter.GetResult()?

I was recently reading some code that uses a lot of async methods, but then sometimes needs to execute them synchronously. The code does: Foo foo = GetFooAsync(...).GetAwaiter().GetResult(); Is this the same as Foo foo = GetFooAsync(...).Result;
Jay Bazuzi
  • 41,333
  • 12
  • 104
  • 161
387
votes
12 answers

How to safely call an async method in C# without await

I have an async method which returns no data: public async Task MyAsyncMethod() { // do some stuff async, don't return any data } I'm calling this from another method which returns some data: public string GetStringData() { MyAsyncMethod();…
George Powell
  • 7,511
  • 8
  • 30
  • 43
386
votes
4 answers

WaitAll vs WhenAll

What is the difference between Task.WaitAll() and Task.WhenAll() from the Async CTP ? Can you provide some sample code to illustrate the different use cases ?
Yaron Levi
  • 10,800
  • 14
  • 59
  • 110
355
votes
2 answers

When correctly use Task.Run and when just async-await

I would like to ask you on your opinion about the correct architecture when to use Task.Run. I am experiencing laggy UI in our WPF .NET 4.5 application (with Caliburn Micro framework). Basically I am doing (very simplified code snippets): public…
Lukas K
  • 5,198
  • 4
  • 17
  • 27
1
2 3
99 100