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++ in C++20
  • Swift in Swift 5.5

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.

C++

Coroutines is introduced in C++20. Using the co_await operator results in suspended execution until resumed. Values can be returned using co_yield and co_return keywords which correspond to suspending and completing execution, respectively.

Swift

The async-await pattern was introduced in Swift 5.5 at WWDC 2021, as part of a broader Swift concurrency initiative. Historically, asynchronous patterns were achieved through the use of Grand Central Dispatch (GCD, ) and “completion handler closure” patterns. The Swift concurrency aims to provide a more intuitive asynchronous coding environment.

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.

Historically, ECMAScript offered “promises”, an improvement over traditional callback patterns, where this sort of looping and exception handling is challenging. Task.js and similar libraries further refined promises, to further simplify the process. But with async functions, all the remaining boilerplate is removed, leaving only the semantically meaningful code in the program text.

Asynchronous vs multi-threaded

The async-await pattern simplifies the writing of asynchronous code. While it is frequently used in multi-threaded environments, it should be noted that “asynchronous” and “multi-threaded” represent two different concepts. The async and await keywords merely allow us to represent relationships and dependencies between asynchronous tasks in a more natural manner, which may be distinct from the mechanism to run code on a different thread. The async-await pattern offers great utility in a multi-threaded environment, but it is not, itself, the multi-threaded mechanism.

Resources:

C#

C++

Swift

Related:

26583 questions
162
votes
4 answers

Should I avoid 'async void' event handlers?

I know it is considered generally a bad idea to use fire-and-forget async void methods to start tasks, because there is no track of the pending task and it is tricky to handle exceptions which might be thrown inside such a method. Should I generally…
avo
  • 10,101
  • 13
  • 53
  • 81
161
votes
11 answers

JavaScript array .reduce with async/await

Seem to be having some issues incorporating async/await with .reduce(), like so: const data = await bodies.reduce(async(accum, current, index) => { const methodName = methods[index] const method = this[methodName] if (methodName == 'foo') { …
benhowdle89
  • 36,900
  • 69
  • 202
  • 331
157
votes
6 answers

'await' works, but calling task.Result hangs/deadlocks

I have the following four tests and the last one hangs when I run it. Why does this happen: [Test] public void CheckOnceResultTest() { Assert.IsTrue(CheckStatus().Result); } [Test] public async void CheckOnceAwaitTest() { …
Johan Larsson
  • 17,112
  • 9
  • 74
  • 88
155
votes
2 answers

Difference between await and ContinueWith

Can someone explain if await and ContinueWith are synonymous or not in the following example. I'm trying to use TPL for the first time and have been reading all the documentation, but don't understand the difference. Await: String webText = await…
Harrison
  • 3,843
  • 7
  • 22
  • 49
153
votes
6 answers

Should I worry about "This async method lacks 'await' operators and will run synchronously" warning

I have a interface which exposes some async methods. More specifically it has methods defined which return either Task or Task. I am using the async/await keywords. I am in the process of implementing this interface. However, in some of these…
dannykay1710
  • 1,953
  • 2
  • 11
  • 13
149
votes
14 answers

ts An async function or method in ES5/ES3 requires the 'Promise' constructor

Hello I'm Using async/await in my TypeScript Project, But I Get this log: [ts] An async function or method in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your…
Saeed Heidarizarei
  • 8,406
  • 21
  • 60
  • 103
149
votes
11 answers

How to know if a function is async?

I have to pass a function to another function, and execute it as a callback. The problem is that sometimes this function is async, like: async function() { // Some async actions } So I want to execute await callback() or callback() depending on…
Facundo Matteo
  • 2,347
  • 2
  • 16
  • 19
149
votes
12 answers

How to limit the amount of concurrent async I/O operations?

// let's say there is a list of 1000+ URLs string[] urls = { "http://google.com", "http://yahoo.com", ... }; // now let's send HTTP requests to each of these URLs in parallel urls.AsParallel().ForAll(async (url) => { var client = new…
Grief Coder
  • 6,508
  • 9
  • 38
  • 51
145
votes
25 answers

How to wait until a predicate condition becomes true in JavaScript?

I have javascript function like this: function myFunction(number) { var x=number; ... ... more initializations //here need to wait until flag==true while(flag==false) {} ... ... do something } The problem is that…
142
votes
9 answers

Is it possible to "await yield return DoSomethingAsync()"

Are regular iterator blocks (i.e. "yield return") incompatible with "async" and "await"? This gives a good idea of what I'm trying to do: async Task> Method(String [] Strs) { // I want to compose the single result to the final…
jiangzhen
  • 1,542
  • 2
  • 10
  • 7
140
votes
2 answers

How do I await multiple promises in-parallel without 'fail-fast' behavior?

I'm using async/await to fire several api calls in parallel: async function foo(arr) { const results = await Promise.all(arr.map(v => { return doAsyncThing(v) })) return results } I know that, unlike loops, Promise.all executes…
Brandon
  • 7,736
  • 9
  • 47
  • 72
139
votes
7 answers

SyntaxError: Unexpected token function - Async Await Nodejs

I was experimenting on using Node version 6.2.1 with some of my code. Had plans to migrate most of the hyper-callback oriented codes to something that looks cleaner and maybe performs better. I have no clue why, the terminal throws up an error when…
bozzmob
  • 12,364
  • 16
  • 50
  • 73
139
votes
4 answers

Effectively use async/await with ASP.NET Web API

I am trying to make use of the async/await feature of ASP.NET in my Web API project. I am not very sure whether it will make any difference in performance of my Web API service. Please find below the workflow and sample code from my…
arp
  • 1,423
  • 2
  • 10
  • 11
137
votes
5 answers

Using async-await on .net 4

I'm currently starting to create an application that would profit a lot from C# 5's async-await feature. But I'm not sure which version of VS and of the async runtime to use. Looking at OS popularity charts, I'll need to support Windows XP for…
CodesInChaos
  • 106,488
  • 23
  • 218
  • 262
137
votes
2 answers

C# 8 understanding await using syntax

I have next method: public async Task> GetQuotesAsync() { using var connection = new SqlConnection(_connectionString); var allQuotes = await connection.QueryAsync(@"SELECT [Symbol], [Bid], [Ask], [Digits] FROM…
Uriil
  • 11,948
  • 11
  • 47
  • 68