Async/await
In computer programming, the async/await pattern is a syntactic feature of many programming languages that allows an asynchronous, non-blocking function to be structured in a way similar to an ordinary synchronous function. It is semantically related to the concept of a coroutine and is often implemented using similar techniques, and is primarily intended to provide opportunities for the program to execute other code while waiting for a long-running, asynchronous task to complete, usually represented by promises or similar data structures. The feature is found in C#, C++, Python, F#, Hack, Julia, Dart, Kotlin, Rust, Nim, JavaScript, and Swift. Source: e01 Encyclopedia. Licence: CC BY-SA 4.0.
In computer programming, the async/await pattern is a syntactic feature of many programming languages that allows an asynchronous, non-blocking function to be structured in a way similar to an ordinary synchronous function. It is semantically related to the concept of a coroutine and is often implemented using similar techniques, and is primarily intended to provide opportunities for the program to execute other code while waiting for a long-running, asynchronous task to complete, usually represented by promises or similar data structures. The feature is found in C#, C++, Python, F#, Hack, Julia, Dart, Kotlin, Rust, Nim, JavaScript, and Swift. Python added support for async/await with version 3.5 in 2015 adding 2 new keywords, async and await . TypeScript added support for async/await with version 1.7 in 2015. JavaScript added support for async/await in 2017 as part of ECMAScript 2017 JavaScript edition. Rust added support for async/await with version 1.39.0 in 2019 using the async keyword and the .await postfix operator, both introduced in the 2018 edition of the language. C++ added support for async/await with version 20 in 2020 with 3 new keywords co_return , co_await , co_yield . Swift added support for async/await with version 5.5 in 2021, adding 2 new keywords async and await . This was released alongside a concrete implementation of the Actor model with the actor keyword which uses async/await to mediate access to each actor from outside. using System; using System.Net.Http; using System.Threading.Tasks; public async Task FindSizeOfPageAsync(Uri uri) { HttpClient client = new(); byte[] data = await client.GetByteArrayAsync(uri); return data.Length; } First, the async keyword indicates to C# that the method is asynchronous, meaning that it may use an arbitrary number of await expressions and will bind the result to a promise. The return type, System.Threading.Tasks.Task , is C#'s analogue to the concept of a promise, and here is indicated to have a result value of type int . (Note that when returning a void , the System.Threading.Tasks.Task class is type-parameterless. The first expression to execute when this method is called will be new HttpClient().GetByteArrayAsync(uri) , which is another asynchronous method returning a Task . Because this method is asynchronous, it will not download the entire batch of data before returning. Instead, it will begin the download process using a non-blocking mechanism (such as a background thread), and immediately return an unresolved, unrejected Task to this function. With the await keyword attached to the Task , this function will immediately proceed to return a Task to its caller, who may then continue on with other processing as needed. Once GetByteArrayAsync() finishes its download, it will resolve the Task it returned with the downloaded data. This will trigger a callback and cause FindPageSizeAsync() to continue execution by assigning that value to data . Finally, the method returns data.Length , a simple integer indicating the length of the array. The compiler re-interprets this as resolving the Task it returned earlier, triggering a callback in the method's caller to do something with that length value. A function using async/await can use as many await expressions as it wants, and each will be handled in the same way (though a promise will only be returned to the caller for the first await, while every other await will utilize internal callbacks). A function can also hold a promise object directly and do other processing first (including starting other asynchronous tasks), delaying awaiting the promise until its result is needed. Functions with promises also have promise aggregation methods that allow the program to await multiple promises at once or in some special pattern (such as C#'s Task.WhenAll() , which returns a valueless Task that resolves when all of the tasks in the arguments have resolved). Many promise types also have additional features beyond what the async/await pattern normally uses, such as being able to set up more than one result callback or inspect the progress of an especially long-running task. In the particular case of C#, and in many other languages with this language feature, the async/await pattern is not a core part of the language's runtime, but is instead implemented with lambdas or continuations at compile time. For instance, the C# compiler would likely translate the above code to something like the following before translating it to its IL bytecode format: using System; using System.Net.Http; using System.Threading.Tasks; public Task FindSizeOfPageAsync(Uri uri) { HttpClient client = new(); Task dataTask = client.GetByteArrayAsync(uri); Task afterDataTask = dataTask.ContinueWith((originalTask) => { return originalTask.Result.Length; }); return afterDataTask; } Because of this, if an interface method needs to return a promise object, but itself does not require await in the body to wait on any asynchronous tasks, it does not need the async modifier either and can instead return a promise object directly. For instance, a function might be able to provide a promise that immediately resolves to some result value (such as C#'s Task.FromResult() ), or it may simply return another method's promise that happens to be the exact promise needed (such as when deferring to an overload). One important caveat of this functionality, however, is that while the code resembles traditional blocking code, the code is actually non-blocking and potentially multithreaded, meaning that many intervening events may occur while waiting for the promise targeted by an await to resolve. For instance, the following code, while always succeeding in a blocking model without await , may experience intervening events during the await and may thus find shared state changed out from under it: using System; using System.Diagnostics; using System.Net.Http; string name = state.name; HttpClient client = new(); byte[] data = await client.GetByteArrayAsync(uri); // Potential failure, as the value of state.name may have // been changed by the handler of an intervening event. Debug.Assert(name == state.name); return data.Length; include include "s_task.h" constexpr int STACK_SIZE = 64 * 1024 / sizeof(int); // define stack memory for tasks int g_stack_main[STACK_SIZE]; int g_stack0[STACK_SIZE]; int g_stack1[STACK_SIZE]; void sub_task(__async__, void* arg) { int n = (int)(size_t)arg; for (int i = 0; i Prior to C++20, there were no equivalents to await , and C++ offered far more limited utilities for asynchronous programming. Notably, C++11 introduced std::promise and std::future which offered a futures and promises model, while std::async() was used to run a function asynchronously (potentially in a separate thread) and return a std::future object, specifically taking a function of type F and returning a future , decay_t ...>> , as well as allowing specifying a std::launch policy. import std; using std::future; using std::launch; using std::vector; // a heavy, CPU-bound operation vector applyFilter(const vector & image) { // ... } int main(int argc, char* argv[]) { // a large amount of data vector imagePixels(5'000'000); std::iota(imagePixels.begin(), imagePixels.end(), 1.0); future > fut = std::async(launch::async, applyFilter, imagePixels); vector processedImage = fut.get(); } C++20 introduced a co_await (prefixed with " " to emphasise its context in coroutines), which is an operator to suspend coroutine execution. along with co_return to terminate and return a value from the coroutine, and co_yield to suspend the coroutine and emit a value back to the caller. A generator class std::generator Inside a coroutine, a task is co_await ed, but outside of coroutines, it can be called using std::this_thread::sync_wait() , which blocks and returns optional > . To be co_await able, a type must implement a number of public member functions, such as await_ready() , await_suspend() , and await_resume() on the return type in order for the type to be awaited on. std::promise and std::future do not implement any of these. import std; using std::optional; using std::tuple; using std::execution::task; using namespace std::literals; task simulateWork() { std::println("Performing work..."); std::this_thread::sleep_for(500ms); std::println("Work done!"); co_return; } task add(int a, int b) noexcept { co_await simulateWork(); co_return a + b; } task test() { int ret = co_await add(1, 2); std::println("Return {}", ret); co_return ret; } int main(int argc, char* argv[]) { optional > result = std::this_thread::sync_wait(test()); std::println("Result: {}", std::get (result.value_or(std::make_tuple(-1)))); // assign empty tuple a sentinel identifier to check for successful completion optional > result = std::this_thread::sync_wait(simulateWork()); if (result.has_value()) { std::println("Work completed successfully."); } else { std::println("Work failed!"); } return 0; } In 2012, C# added the async/await pattern in C# with version 5.0, which Microsoft refers to as the task-based asynchronous pattern (TAP). Async methods usually return either void , System.Threading.Tasks.Task (a " void task"), System.Threading.Tasks.Task , System.Threading.Tasks.ValueTask (a " void value task") or System.Threading.Tasks.ValueTask . User code can define custom types that async methods can return through custom async method builders but this is an advanced and rare scenario. Async methods that return void are intended for event handlers; in most cases where a synchronous method would return void , returning Task instead is recommended, as it allows for more intuitive exception handling (note that Task is invalid in C#). Methods that make use of await must be declared with the async keyword. In methods that have a return value of type Task , methods declared with async must have a return statement of type assignable to T instead of Task ; the compiler wraps the value in the Task generic. It is also possible to await methods that have a return type of Task or Task that are declared without async . The following async method downloads data from a URL using await . Because this method issues a task for each URI before requiring completion with the await keyword, the resources can load at the same time instead of waiting for the last resource to finish before starting to load the next. namespace Wikipedia.Examples; using System; using System.Collections.Generic; using System.Net.Http; using System.Threading.Tasks; public class Example { public async Task SumPageSizesAsync(IEnumerable uris) { HttpClient client = new(); int total = 0; List > loadUriTasks = new(); foreach (Uri uri in uris) { byte[] loadUriTask = client.GetByteArrayAsync(uri); loadUriTasks.Add(loadUriTask); } foreach (Task > loadUriTask in loadUriTasks) { statusText.Text = $"Found {total} bytes ..."; byte[] resourceAsBytes = await loadUriTask; total += resourceAsBytes.Length; } statusText.Text = $"Found {total} bytes total"; return total; } static async Task Main(string[] args) { List uris = new { new Uri("https://en.wikipedia.org"), new Uri("https://www.microsoft.com"), new Uri("https://www.github.com") } int totalBytes = await SumPageSizesAsync(uris); Console.WriteLine($"Total bytes downloaded: {totalbytes}"); } } In 2007, F# added asynchronous workflows with version 2.0. The asynchronous workflows are implemented as CE (computation expressions). They can be defined without specifying any special context (like async in C#). F# asynchronous workflows append a bang (!) to keywords to start asynchronous tasks. The following async function downloads data from an URL using an asynchronous workflow: let asyncSumPageSizes (uris: #seq ) : Async = async { use httpClient = new HttpClient() let! pages = uris |> Seq.map(httpClient.GetStringAsync >> Async.AwaitTask) |> Async.Parallel return pages |> Seq.fold (fun accumulator current -> current.Length + accumulator) 0 } Java does not have async and await keywords in the language, however it can be emulated using the java.util.concurrent package, such as the class java.util.concurrent.CompletableFuture (introduced in Java 8). Asynchronous programming is later improved in Java 21 with the introduction of virtual threads and structured task scopes. package org.wikipedia.examples; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.StructuredTaskScope; public class AsyncExample { public String fetchData() { // Simulate a time-consuming operation (e.g., network request, database query) try { Thread.sleep(2000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } return "Data from remote source"; } public CompletableFuture fetchDataAsync() { return CompletableFuture.supplyAsync(() -> fetchData()); } public static void main(String[] args) throws ExecutionException, InterruptedException { AsyncExample example = new AsyncExample(); // Using CompletableFuture (Java 8) System.out.println("Starting asynchronous operation..."); CompletableFuture future = example.fetchDataAsync(); System.out.println("Doing other work..."); // Wait for the result (similar to 'await') String result = future.get(); System.out.printf("Received result: %s%n", result); // Using Virtual Threads (Java 21): ExecutorService extor = Executors.newVirtualThreadPerTaskExecutor(); System.out.println("Starting virtual thread operation..."); Future fut = extor.submit(() -> { return example.fetchData(); }); System.out.println("Doing other work..."); String result = future.get(); System.out.printf("Received result: %s%n", result); extor.shutdown(); // Using StructuredTaskScope (Java 21) try (StructuredTaskScope.ShutdownOnFailure scope = new StructuredTaskScope.ShutdownOnFailure()) { StructuredTaskScope.Subtask dataTask = scope.fork(example::fetchData); System.out.println("Doing other work..."); scope.join(); // wait for all tasks scope.throwIfFailed(); // propagate if any exceptions String result = future.get(); System.out.printf("Received result: %s%n", result); } } } The await operator in JavaScript (and TypeScript) can only be used from inside an async function or at the top level of a module. If the parameter is a promise, execution of the async function will resume when the promise is resolved (unless the promise is rejected, in which case an error will be thrown that can be handled with normal JavaScript exception handling). If the parameter is a thenable object, a new promise will be constructed with the native Promise constructor by calling the object's then() method and passing in a handler that calls the resolve callback. Otherwise, the parameter itself will be returned immediately. Many libraries provide promise objects that can also be used with await , as long as they match the specification for native JavaScript promises. However, promises from the jQuery library were not Promises/A+ compatible until jQuery 3.0. Below is an example (modified from this article): interface DBResponse { id: string; rev?: string; ok?: boolean; } interface Document { _id: string; _rev?: string; [key: string]: any; } interface Database { post(doc: object): Promise ; get(id: string): Promise ; } declare const db: Database; async function createNewDoc(): Promise { const response: DBResponse = await db.post({}); const doc: Document = await db.get(response.id); return doc; } async function main(): Promise { try { const doc: Document = await createNewDoc(); console.log(doc); } catch (err: Error) { console.error("Error creating or fetching document:", err); } } main(); Node.js version 8 includes a utility that enables using the standard library callback-based methods as promises. Kotlin uses coroutines with async() (from kotlinx.coroutines.CoroutineScope ) and await() (from kotlinx.coroutines.Deferred ) methods, rather than true async / await keywords. For example, the following uses async and await() methods for parallel execution. import kotlinx.coroutines.* import kotlin.system.measureTimeMillis suspend fun fetchFirstData(): String { delay(1000) // simulates a network call return "Data from server A" } suspend fun fetchSecondData(): String { delay(1000) // simulates a network call return "Data from server B" } suspend fun main() = coroutineScope { val time = measureTimeMillis { // Start both network requests at the same time in the background val deferredOne: Deferred = async { fetchFirstData() } val deferredTwo: Deferred = async { fetchSecondData() } // Wait for both results to finish val resultOne = deferredOne.await() val resultTwo = deferredTwo.await() println("Combined results: $resultOne & $resultTwo") } println("Completed in $time ms") } import asyncio async def main() -> None: print("hello") await asyncio.sleep(1) print("world") if __name__ == "__main__": asyncio.run(main()) async is a specifier that marks an expression as returning a std::future::Future (rather than blocking the thread) , while await is an operator (used with .await ), which suspends execution until the std::future::Future result is ready. // In the crate's Cargo.toml, we need `futures = "0.3.0"` in the dependencies section, // so we can use the futures crate extern crate futures; // There is no executor currently in the `std` library. use std::future::Future; // This desugars to something like // `fn async_add_one(num: u32) -> impl Future ` async fn async_add_one(num: u32) -> u32 { num + 1 } async fn example_task() { let number = async_add_one(5).await; println!("5 + 1 = {}", number); } fn main() { // Creating the Future does not start the execution. let future = example_task(); // The `Future` only executes when we actually poll it, unlike JavaScript. futures::executor::block_on(future); } func getNumber() async throws -> Int { try await Task.sleep(nanoseconds: 1_000_000_000) return 42 } Task { let first = try await getNumber() let second = try await getNumber() print(first + second) }
Cite this
"Async/await". 1789533611. e01 Encyclopedia. CC BY-SA 4.0. https://en.wikipedia.org/w/index.php?oldid=1375175554 JSON record · API collection · BibTeX · RIS · CSL-JSON · citation policy