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
73
votes
3 answers

Debugger not breaking/stopping for exceptions in async method

When a debugger is attached to a .NET process, it (usually) stops when an unhandled exception is thrown. However, this doesn't seem to work when you're in an async method. The scenarios I've tried before are listed in the following code: class…
72
votes
9 answers

How to use Array.prototype.filter with async?

Background I am trying to filter an array of objects. Before I filter, I need to convert them to some format, and this operation is asynchronous. const convert = () => new Promise( resolve => { setTimeout( resolve, 1000 ); }); So, my first…
Flame_Phoenix
  • 16,489
  • 37
  • 131
  • 266
72
votes
2 answers

The 'await' operator can only be used within an async lambda expression

I've got a c# Windows Store app. I'm trying to launch a MessageDialog when one of the command buttons inside another MessageDialog is clicked. The point of this is to warn the user that their content is unsaved, and if they click cancel, it will…
roryok
  • 9,325
  • 17
  • 71
  • 138
72
votes
6 answers

How to construct a Task without starting it?

I want to use this Task constructor. I can't seem to get the syntax right. Could someone correct my code? Also, am I right thinking that if a Task is constructed that way, it's not started? The constructor I think I need…
G. Stoynev
  • 7,389
  • 6
  • 38
  • 49
72
votes
5 answers

Cannot implicitly convert type from Task<>

I am trying to master async method syntax in .NET 4.5. I thought I had understood the examples exactly however no matter what the type of the async method is (ie Task), I always get the same type of error error on the conversion back to T -…
PaulR
  • 861
  • 1
  • 8
  • 11
71
votes
5 answers

Async function with +=

let x = 0; async function test() { x += await 5; console.log('x :', x); } test(); x += 1; console.log('x :', x); The values of x logged are 1 and 5. My question is: why is the value of x 5 on second log? If the test is executed after x…
Aldrin
  • 2,036
  • 15
  • 12
70
votes
12 answers

Asynchronous Task.WhenAll with timeout

Is there a way in the new async dotnet 4.5 library to set a timeout on the Task.WhenAll method? I want to fetch several sources, and stop after say 5 seconds, and skip the sources that weren't finished.
broersa
  • 1,656
  • 3
  • 16
  • 31
70
votes
3 answers

Asynchronous calls with React.useMemo

Scenario is relatively simple: we have a long-running, on-demand calculation that occurs on a remote server. We want to memoize the result. Even though we are fetching asychronously from a remote resource, this isn't a side effect because we just…
Doug Denniston
  • 894
  • 1
  • 8
  • 12
70
votes
4 answers

Unexpected `await` inside a loop. (no-await-in-loop)

How Should I await for bot.sendMessage() inside of loop? Maybe I Need await Promise.all But I Don't Know How Should I add to bot.sendMessage() Code: const promise = query.exec(); promise.then(async (doc) => { let count = 0; for (const val of…
Saeed Heidarizarei
  • 8,406
  • 21
  • 60
  • 103
69
votes
3 answers

React TypeScript 16.8 How to make useEffect() async

Why can't useEffect() use async-await? const Home: React.FC = () => { useEffect(async () => { console.log(await ecc.randomKey()) }, []) return ( ... The error I get is Argument of type '() => Promise' is not…
Bill
  • 4,614
  • 13
  • 77
  • 132
69
votes
5 answers

Is async await truly non-blocking in the browser?

I have been playing around with the feature in an SPA using TypeScript and native Promises, and I notice that even if I refactor a long-running function into an async function returning a promise, the UI is still unresponsive. So my questions…
prmph
  • 7,616
  • 11
  • 37
  • 46
68
votes
5 answers

Why await is not working for node request module?

I'm new to nodejs. I’m not seeing the response in ex 1, but i see in ex 2. Why? Await works for me in other places, using babel. Ex 1 let res = await request(url) console.log(res); console.log(res.body); Ex 2 request(url, function (error, res,…
user43286
  • 2,261
  • 3
  • 31
  • 42
68
votes
4 answers

Lock and Async method in C#

I am not clear (and can't find documentation clear enough): when using the lock keyword in an async method: will the thread be blocked if the object is already blocked or will it return a task in suspended state (not blocking the thread, and…
rufo
  • 5,158
  • 2
  • 36
  • 47
68
votes
2 answers

How to await an async private method invoked using reflection in WinRT?

I'm writing unit tests for a WinRT app, and I am able to invoke non-async private methods using this: TheObjectClass theObject = new TheObjectClass(); Type objType = typeof(TheObjectClass); objType.GetTypeInfo() …
jokeefe
  • 1,836
  • 4
  • 22
  • 27
67
votes
3 answers

async await in image loading

Temp.js export default class Temp { async addImageProcess(src){ let img = new Image(); img.src = src; return img.onload = await function(){ return this.height; } } } anotherfile.js import Temp from…
Rahul
  • 1,013
  • 1
  • 10
  • 24