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
10
votes
1 answer

Why doesn't await Task.Run() sync back to UI Thread / origin context?

I thought I understood the async-wait pattern and the Task.Run operation. But I am wondering why in the following code example the await does not sync back to the UI thread after returning from the finished task. public async Task…
rittergig
  • 715
  • 1
  • 5
  • 16
10
votes
4 answers

How to handle multiple awaits in async function

I have multiple API calls to be made which fetch via an API, write data to DB via API, send output to front end via another API. I have written async function with await like below. The first two should run one after another but the third one can…
Yasar Abdullah
  • 181
  • 2
  • 2
  • 4
10
votes
1 answer

What is a canonical safe way of async lazy initialization in javascript?

I have this sort of lazy initialization code in my program: let user = null; let getUser = async () => { if(!user) { user = await getUserSomehow(); } return user; }; I understand that it is not safe, due to a possible race…
Arsenii Fomin
  • 3,120
  • 3
  • 22
  • 42
10
votes
2 answers

How do I wait for an async function to finish executing before rendering a widget in Flutter

On my main.dart file, I want to check if a user is logged so as to direct him to the appropriate screen. I am using SharedPrefence to store user detail from Firebase. How do I tell my function to wait until my SharedPreference async function…
Ilo Calistus
  • 2,005
  • 3
  • 19
  • 23
10
votes
1 answer

(async () => { })(); what is this?

async function test() { (async () => { var a = await this.test1(); var b = await this.test2(a); var c = await this.test3(b); this.doThis(a,b,c); })(); } What does it mean to put…
bbusdriver
  • 1,577
  • 3
  • 26
  • 58
10
votes
1 answer

How to assert for an error using axios and async / await

I am trying to write a test that asserts that a specific type of error is thrown with Async / Await and axios. However, when I run my test, I get the following. Why is jest not properly rejecting my promise? Thanks! Error:…
Jimmy
  • 3,090
  • 12
  • 42
  • 99
10
votes
1 answer

How to debug code after await in Typescript in Vscode?

I am on Vscode 1.33.1, Node 11.12, Typescript 3.4.3, vscode-chrome-debug-core 6.7.46 and I'm trying to debug a React Native project. As long as I don't hit await, everything works perfectly. However, when I hit a line that contains await, I don't…
Can Poyrazoğlu
  • 33,241
  • 48
  • 191
  • 389
10
votes
2 answers

How to make arrow function async?

I have the following code that checks the existance of a file and if present, parses the JSON data from it: fs.access(dbPath, (err) => { if (err) throw err else{ console.log('Database found. Processing data.'); …
VikingPingvin
  • 382
  • 5
  • 16
10
votes
2 answers

debugging async C# in visual studio; breaking on exceptions as expected

I'm struggling to figure out how to use visual studio to debug async code sanely, since it's not breaking where I want it to. For example, in this code: using System; using System.Threading.Tasks; namespace TestNS{ class Program { …
Chucky Ellison
  • 470
  • 6
  • 14
10
votes
1 answer

vuejs rendering async function in template displays promise instead of returned data

I am calling an async function which loads the profile pic, the await call returns the value to the variable 'pf' as expected, but I couldn't return that from loadProfilePic. At least for the start I tried to return a static string to be displayed…
Code Tree
  • 2,160
  • 4
  • 26
  • 39
10
votes
1 answer

kotlin coroutine - how to ensure some commands run on UI main thread when invoked inside coroutine?

i have a very simple coroutine that just does some delay and then what i want it to do is post commands to UI message queue. so run the last two lines on UI thread. here is the coroutine: async{ delay(5000) doSomething() …
j2emanue
  • 60,549
  • 65
  • 286
  • 456
10
votes
2 answers

await doesn't wait for the function to end

I'm new to javascript and I tried to implement my first async await and can't figure out where is my problem. getName() - should return a promise after 1s. f() - should wait for getName to finish and then print name What am I missing ? const getName…
Htpc Rad
  • 133
  • 1
  • 1
  • 7
10
votes
1 answer

Why use async pattern in Node.js CPU-bound code?

I am using bcrypt in NodeJS to generate password hash. Bcrypt docs says that we can use async version of the genSalt(), compare() and hash() functions. NodeJS is single-threaded, so theoretically if I use a CPU-bound code will block the thread even…
Gustavo Piucco
  • 467
  • 1
  • 7
  • 17
10
votes
2 answers

Flutter/Dart Async Not Waiting

I'm building my first Flutter application and I've run into a bit of an async issue. When my application executes I'd like it to ask for permissions and wait until they are granted. My main() function looks like this: import…
Topazoo
  • 113
  • 1
  • 1
  • 5
10
votes
1 answer

Is it possible to use async/await for Publishing a message to RabbitMQ?

I can't seem to find any information about how to async'ly Publish a message to RabbitMQ. The examples I stumble across are usually about using async/await to retrieve/consume a message from RabbitMQ. var consumer = new…
Pure.Krome
  • 84,693
  • 113
  • 396
  • 647