Conceptcore
Futures and promises
Also called futures, promises, future, promise, deferred, task, eventual value, CompletableFuture, Promise.
A future is a placeholder for the result of a computation that has not finished. A promise is the side that sets the result once. Code can wait for the value, or attach the next step to it.
- Applies to
- core-languages
Idea
A slow operation, such as a network request, a disk read or a long calculation, does not have its result at the time of the call. A future is an object that stands for that result before it exists. The caller gets the future at once and continues with other work. Later, the caller reads the value from the future, and waits only if the value is not ready yet. A promise is the other side of the same object: the code that does the work uses the promise to store the value, or an error, exactly one time.
import time
from concurrent.futures import ThreadPoolExecutor
def fetch(name):
time.sleep(0.05)
return f"{name} loaded"
with ThreadPoolExecutor() as pool:
future = pool.submit(fetch, "profile")
print("request sent, done:", future.done())
print(future.result())
print("done:", future.done())
request sent, done: False
profile loaded
done: True
The names are not used the same way in all languages. In JavaScript, Promise is the name of the object that the caller reads. In C++, std::promise is the write side and std::future is the read side. Java has Future and CompletableFuture, C# has Task, Kotlin has Deferred, and Rust has the Future trait. All of them are a placeholder for a value that a computation will make later.
How it works
A placeholder with states. The ECMAScript specification defines a promise as "an object that is used as a placeholder for the eventual results of a deferred (and possibly asynchronous) computation". A promise is pending, fulfilled or rejected, and "a promise is said to be settled if it is not pending, i.e. if it is either fulfilled or rejected."1 The change from pending to settled occurs one time only. The specification states: "Attempting to resolve or reject a resolved promise has no effect".1 Java gives the same rule for threads that race: "When two or more threads attempt to complete, completeExceptionally, or cancel a CompletableFuture, only one of them succeeds."2 Because the value can never change after it is set, many readers can share it without a lock.
Two sides. The C++ library shows the two roles as two types. std::promise "provides a facility to store a value or an exception that is later acquired asynchronously via a std::future object created by the std::promise object".3 std::future "provides a mechanism to access the result of asynchronous operations".4 Other libraries put both roles in one object, or hide the write side. A JavaScript Promise gives resolve and reject only to the function passed to its constructor.5 A C# TaskCompletionSource and a Java CompletableFuture expose the write side as methods. Python's asyncio.Future has set_result and set_exception, and the documentation states that these objects "are used to bridge low-level callback-based code with high-level async/await code."6
Read by waiting. The first futures were read with a blocking call. The Java Future interface represents "the result of an asynchronous computation", and the program retrieves the result "using method get when the computation has completed, blocking if necessary until it is ready."7 Python's Future.result() is the same, and "if the call raised an exception, this method will raise the same exception."8 A blocking read is simple, but it holds a whole thread while it waits.
Read by callback. A newer style attaches the next step to the future and does not wait. Promises/A+ states: "A promise represents the eventual result of an asynchronous operation. The primary way of interacting with a promise is through its then method".9 then returns a new promise for the result of the callback, so a program can chain steps, and an error skips to the next rejection handler, as an exception skips to the next catch. Java CompletableFuture has thenApply, thenCompose and thenCombine for the same purpose.2 async and await are syntax over this model: await gives the rest of the function to the future as its callback.
Eager or lazy. In most languages, the work starts when the future is made. The .NET guidelines state that tasks "begin their life cycle in a hot state, which means that the asynchronous operations they represent are already initiated".10 A JavaScript promise also runs its executor function at once. Rust is different. A Rust future "is a value that might not have finished computing yet",11 and its poll method "does not block if the value is not ready. Instead, the current task is scheduled to be woken up when it's possible to make further progress".11 Nothing calls poll until a program awaits the future or gives it to an executor. The Rust book states: "futures in Rust are lazy: they don't do anything until you ask them to with the await keyword."12
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Standard library | |
| C++ | Standard library | |
| Java | Standard library | |
| C | Absent | |
| C# | Native | |
| JavaScript | Native | |
| TypeScript | Native | |
| Go | Idiom | |
| Rust | Native | |
| Kotlin | Library | The async builder of kotlinx.coroutines returns a Deferred, a future that a coroutine reads with await(); no example file because kotlinc is not installed on the machine that recorded the examples. Alternative: Java.util.concurrent.CompletableFuture on the JVM. |
| SQL | Does not apply | A statement runs to completion in its session, and asynchronous execution belongs to the client library. |
| Bash | Idiom | |
| PowerShell | Native | Start-Job and Start-ThreadJob return a job object, and Receive-Job and Wait-Job wait for its output; no example file because pwsh is not installed on the machine that recorded the examples. |
| HTML | Does not apply | HTML has no concurrency. |
| CSS | Does not apply | CSS has no concurrency. |
| Regular expressions | Does not apply | A regular expression has no concurrency. |
| Language | Verdict | Mechanism |
|---|---|---|
| Python | stdlib | concurrent.futures.Future, asyncio.Future, asyncio.Task |
| JavaScript | native | Promise, then, await |
| TypeScript | native | Promise<T> |
| Java | stdlib | Future, CompletableFuture |
| Kotlin | library | Deferred in kotlinx.coroutines |
| C# | native | Task<T>, TaskCompletionSource<T>, await |
| Go | idiom | a goroutine and a channel with a buffer of one |
| Rust | native | the Future trait, async, .await, an executor crate |
| C | absent | a thread and a join, or callbacks on an event loop |
| C++ | stdlib | std::promise, std::future, std::async |
| Bash | idiom | &, $! and wait |
| PowerShell | native | Start-Job, Receive-Job, Wait-Job |
| SQL | n/a | the client library runs statements asynchronously |
| Regex, HTML, CSS | n/a | no concurrency |
Python has two future types. concurrent.futures.Future belongs to a pool of threads or processes: "The Future class encapsulates the asynchronous execution of a callable. Future instances are created by Executor.submit()".8 asyncio.Future belongs to an event loop, and a coroutine reads it with await.6
JavaScript and TypeScript make all asynchronous APIs of the platform return a Promise. MDN describes it as "a proxy for a value not necessarily known when the promise is created", so that "instead of immediately returning the final value, the asynchronous method returns a promise to supply the value at some point in the future."5 Handlers always run as later jobs, after the current code ends, even when the promise is already settled.1
Java has the blocking Future interface and CompletableFuture, "a Future that may be explicitly completed (setting its value and status), and may be used as a CompletionStage".2 Kotlin uses the async builder of kotlinx.coroutines, which returns a Deferred. The Kotlin documentation calls it a light-weight non-blocking future, and a coroutine reads its value with await().13
C# uses Task<T> for all asynchronous work, and await reads it without a blocked thread.10
Go has no future type. A function starts a goroutine and returns a channel that will receive the result.
Rust has the Future trait in the standard library, but no executor. A crate such as Tokio polls futures and wakes them when I/O is ready.12 std::thread::spawn returns a JoinHandle, which is a blocking future for the result of a thread.
C has no future type. C++ has std::promise, std::future, std::shared_future and std::async. A std::future is "a unique reference to the result in a shared state", so only one reader can call get.4
Bash starts a command in the background with &, and wait with the process ID returns its exit status.
import asyncio
from concurrent.futures import ThreadPoolExecutor
def square(n):
return n * n
with ThreadPoolExecutor(max_workers=2) as pool:
futures = [pool.submit(square, n) for n in range(4)]
print([f.result() for f in futures])
async def main():
loop = asyncio.get_running_loop()
future = loop.create_future()
loop.call_soon(future.set_result, "ready")
print(future.done())
print(await future, future.done())
results = await asyncio.gather(asyncio.sleep(0, "a"), asyncio.sleep(0, "b"))
print(results)
asyncio.run(main())
[0, 1, 4, 9]
False
ready True
['a', 'b']
- Verdict: stdlib.
concurrent.futuresruns a callable in a pool of threads or processes, andsubmitreturns aFutureat once.result()waits for the value or raises the exception of the call. asyncio.Futureis the future of the event loop. A coroutine waits for it withawait. Code that sets the result plays the role of the promise.asyncio.gatherwaits for many awaitables and returns their results in the order of the arguments.
This code runs but gives a wrong answer on purpose.
from concurrent.futures import ThreadPoolExecutor
def save(record):
raise ValueError(f"bad record {record}")
with ThreadPoolExecutor() as pool:
pool.submit(save, 1)
print("all saved")
all saved
The exception is stored in the future, and nothing reads the future. The program reports success. Keep the futures and call result() on each one, or use pool.map, which raises the first exception.
#include <future>
#include <iostream>
#include <stdexcept>
#include <thread>
int main() {
std::future<int> price = std::async(std::launch::async, [] { return 40; });
std::cout << price.get() + 2 << "\n";
std::promise<std::string> promise;
std::future<std::string> result = promise.get_future();
std::thread worker([&promise] { promise.set_value("done"); });
std::cout << result.get() << "\n";
worker.join();
auto failing = std::async(std::launch::async, []() -> int { throw std::runtime_error("no stock"); });
try {
failing.get();
} catch (const std::runtime_error& e) {
std::cout << "caught: " << e.what() << "\n";
}
}
42
done
caught: no stock
- Verdict: stdlib.
std::promisestores a value or an exception once, and thestd::futurethat it makes reads it once withget.std::asyncruns a callable and returns its future. std::futurehas nothen, so a program cannot chain work without a blocked thread.std::shared_futurelets many readers wait for the same value.
This code runs but gives a wrong answer on purpose.
#include <chrono>
#include <future>
#include <iostream>
#include <thread>
void slow_log() {
std::this_thread::sleep_for(std::chrono::milliseconds(50));
std::cout << "log written\n";
}
int main() {
std::async(std::launch::async, slow_log);
std::cout << "main continues\n";
}
log written
main continues
The future from std::async is a temporary. Its destructor waits until the task ends, so the call runs as if it were synchronous. Keep the future in a variable for as long as the work must run in the background.
import java.util.concurrent.CompletableFuture;
public class Main {
public static void main(String[] args) {
CompletableFuture<Integer> price = CompletableFuture.supplyAsync(() -> 40);
CompletableFuture<Integer> tax = CompletableFuture.supplyAsync(() -> 2);
int total = price.thenCombine(tax, Integer::sum).join();
System.out.println(total);
CompletableFuture<String> manual = new CompletableFuture<>();
new Thread(() -> manual.complete("done")).start();
System.out.println(manual.join());
String recovered = CompletableFuture.<String>supplyAsync(() -> {
throw new IllegalStateException("no stock");
}).exceptionally(e -> "fallback: " + e.getCause().getMessage()).join();
System.out.println(recovered);
}
}
42
done
fallback: no stock
- Verdict: stdlib.
Futureis the read side:getwaits for the result.CompletableFutureis also the write side: any thread can callcompleteorcompleteExceptionallyonce. thenApply,thenComposeandthenCombinemake new futures from old ones without a wait.joinwaits and wraps a failure in an uncheckedCompletionException.
#include <pthread.h>
#include <stdio.h>
struct job {
int input;
int result;
};
static void *square(void *arg) {
struct job *job = arg;
job->result = job->input * job->input;
return NULL;
}
int main(void) {
struct job job = {.input = 7};
pthread_t thread;
if (pthread_create(&thread, NULL, square, &job) != 0) {
return 1;
}
pthread_join(thread, NULL);
printf("%d\n", job.result);
return 0;
}
49
- Verdict: absent. C has no future type. A thread writes its result into memory that the caller owns, and
pthread_joinorthrd_joinwaits for the thread. After the join, the caller can read the result safely. - A real future in C needs a mutex and a condition variable, or a library such as libuv for callbacks on an event loop.
var price = Task.Run(() => 40);
var tax = Task.Run(() => 2);
int[] parts = await Task.WhenAll(price, tax);
Console.WriteLine(parts.Sum());
var source = new TaskCompletionSource<string>();
_ = Task.Run(() => source.SetResult("done"));
Console.WriteLine(await source.Task);
try
{
await Task.Run(() => throw new InvalidOperationException("no stock"));
}
catch (InvalidOperationException e)
{
Console.WriteLine("caught: " + e.Message);
}
42
done
caught: no stock
- Verdict: native.
Task<T>is the future type of .NET, andawaitwaits for it without a blocked thread.TaskCompletionSource<T>is the promise side. - A task that a method returns is already started.
awaitrethrows the exception of the task. .Resultand.Wait()block the thread. In code with a synchronization context, such as a UI thread, they can deadlock.
const ready = new Promise((resolve) => resolve("ready"));
ready.then((value) => console.log("then:", value));
console.log("sync code runs first");
const delay = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));
const results = await Promise.all([delay(20, "a"), delay(10, "b")]);
console.log(results);
const settled = await Promise.allSettled([delay(5, "ok"), Promise.reject(new Error("failed"))]);
console.log(settled.map((r) => r.status));
sync code runs first
then: ready
[ 'a', 'b' ]
[ 'fulfilled', 'rejected' ]
- Verdict: native. A
Promiseis pending, fulfilled or rejected. The executor function passed to the constructor getsresolveandreject, which are the promise side.thenandawaitare the future side. - A handler always runs after the current code, as a microtask, even when the promise is already fulfilled.
Promise.allkeeps the order of its inputs and rejects as soon as one input rejects.Promise.allSettledwaits for all of them.
This code runs but gives a wrong answer on purpose.
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const saved = [];
[1, 2, 3].forEach(async (n) => {
await delay(5);
saved.push(n);
});
console.log("saved:", saved.length);
saved: 0
forEach ignores the promises that the async callback returns, so the code after it does not wait. Use for (const n of items) await ... for one at a time, or await Promise.all(items.map(async (n) => ...)) for all at once.
function withTimeout<T>(work: Promise<T>, ms: number): Promise<T> {
const timeout = new Promise<never>((_, reject) =>
setTimeout(() => reject(new Error(`timed out after ${ms} ms`)), ms),
);
return Promise.race([work, timeout]);
}
const slow = new Promise<number>((resolve) => setTimeout(() => resolve(42), 50));
const fast = Promise.resolve(7);
console.log(await withTimeout(fast, 20));
try {
await withTimeout(slow, 20);
} catch (e) {
console.log((e as Error).message);
}
7
timed out after 20 ms
- Verdict: native.
Promise<T>carries the type of the value. A rejection has no type, socatchgetsunknownin strict mode. Promise.racesettles with the first input that settles. The slower promise keeps running, because a promise cannot be cancelled. AnAbortSignalis the usual way to stop the work.
package main
import (
"fmt"
"time"
)
func async[T any](work func() T) <-chan T {
result := make(chan T, 1)
go func() {
result <- work()
}()
return result
}
func main() {
price := async(func() int {
time.Sleep(10 * time.Millisecond)
return 40
})
tax := async(func() int { return 2 })
fmt.Println(<-price + <-tax)
}
42
- Verdict: idiom. Go has no future type. A goroutine that sends its result on a channel with a buffer of one is the usual replacement. The buffer lets the goroutine finish even if no one reads the result.
- A receive from the channel waits for the value. To wait for many goroutines and get the first error, the
golang.org/x/sync/errgrouppackage is common.
use std::future::Future;
use std::pin::pin;
use std::task::{Context, Poll, Waker};
use std::thread;
fn block_on<F: Future>(future: F) -> F::Output {
let mut future = pin!(future);
let mut cx = Context::from_waker(Waker::noop());
loop {
if let Poll::Ready(value) = future.as_mut().poll(&mut cx) {
return value;
}
thread::yield_now();
}
}
async fn price() -> i32 {
println!("price runs");
40
}
fn main() {
let future = price();
println!("future created");
println!("{}", block_on(future) + 2);
let handle = thread::spawn(|| 6 * 7);
println!("{}", handle.join().unwrap());
}
future created
price runs
42
42
- Verdict: native. An
async fnreturns a value that implementsFuture. Futures in Rust are lazy: the body does not run until something polls the future, usually through.await. - The standard library has the
Futuretrait but no executor. Programs use a runtime crate, such as Tokio, to poll futures and wake them when I/O is ready. This example uses a minimal executor that only works for futures that never wait. thread::spawnreturns aJoinHandle, which acts as a future for a thread:joinwaits for the result.
work() {
sleep 0.1
echo "$1" > "result-$1.txt"
return "$2"
}
work a 0 &
first=$!
work b 3 &
second=$!
wait "$first"
echo "a exited with $? and wrote $(cat result-a.txt)"
wait "$second"
echo "b exited with $?"
a exited with 0 and wrote a
b exited with 3
- Verdict: idiom.
&starts a command in the background, and$!is its process ID.waitwith the ID waits for that process and returns its exit status. The process ID works as a future for the exit status. - A background process cannot set variables in the shell, so the result goes through a file or a pipe.
Variations and related ideas
Implicit futures. In Multilisp and some later languages, a future is a transparent value. An operation that needs the real value waits for it with no explicit read, and code that only passes the value on does not wait.
Promise pipelining. In a distributed system, a program can send a message to the result of a remote call before the result arrives. The remote side forwards the message when the value is ready, so that a chain of calls takes one network round trip and not many.
Dataflow variables. A single-assignment variable, which a thread can read before another thread binds it, is a future without a separate object. Oz and some parallel languages use this model.
Futures and threads. A future is a value. A thread is a unit of execution. A join on a thread gives the result of the thread, so a thread handle with a result is one kind of future. See threads.
Futures and channels. A future carries one value and keeps it. A channel carries a sequence of values, and each receive removes one. A channel with a buffer of one, used one time, acts as a future. See channels.
Streams of values. An async iterator or an observable is the many-values form of a future: the consumer receives a sequence of results over time.
Async and await. async functions return a future, and await suspends the function until the future settles. See async/await.
Pitfalls
A lost error. A future stores an exception until a program reads it. If no code reads the future, the error is lost and the program continues as if the work succeeded.8 JavaScript runtimes report a rejection with no handler, but only as a warning or a process exit, at a time after the error.
A floating promise. A call to an asynchronous function without await starts the work and drops the future. In JavaScript, forEach with an async callback has this problem: the loop ends before the work ends. Linters can find promises that nothing awaits or handles.
A blocked event loop. A blocking read of a future on the thread that must complete the future causes a deadlock. In C#, .Result or .Wait() on a UI thread can wait for a continuation that needs that same thread.
A future that blocks in its destructor. In C++, "if the std::future obtained from std::async is not moved from or bound to a reference, the destructor of the std::future will block at the end of the full expression until the asynchronous operation completes".14 A call to std::async that ignores the result is therefore synchronous.
Sequential waits. A loop that awaits each step in turn runs the steps one after another. If the steps are independent, start all of them first, and then wait for all of them with Promise.all, Task.WhenAll or asyncio.gather.
No cancellation. A JavaScript promise cannot be cancelled. If a program stops waiting, for example after a timeout with Promise.race, the work continues. Cancellation must come from a separate object, such as an AbortSignal or a CancellationToken. A future that nobody needs any more still uses resources until it ends. Baker and Hewitt described this problem as early as 1977: "futures which were thought to be relevant when they were created become irrelevant through being ignored in the body of the expression where they were bound."15
Lazy futures that never run. In Rust, a future that no code awaits or spawns never runs. The compiler warns because futures are #[must_use].
Cost
A future is usually a small object on the heap, with a state, a value slot and a list of callbacks. Each callback is a closure, and each then makes a new future. A blocking read holds a thread until the value is ready. A callback or await holds no thread, but adds one scheduling step per continuation. A Rust async fn compiles to a state machine. That state machine is a value that does not need a heap allocation, unless the program boxes it or spawns it on an executor. Futures do not make the work faster. They let independent work overlap, so the total time can drop to the time of the slowest task.
History
Henry Baker and Carl Hewitt described futures in 1977 in "The Incremental Garbage Collection of Processes". In their call-by-future, "each formal parameter of a function is bound to a separate process (called a "future") dedicated to the evaluation of the corresponding argument. This mechanism allows the fully parallel evaluation of arguments to a function".15 Daniel Friedman and David Wise had used the word promise in 1976 for a similar construct. Robert Halstead made future a central construct of Multilisp, a parallel Lisp, in 1985. Barbara Liskov and Liuba Shrira, in 1988, used promises for asynchronous remote procedure calls. The E language and its predecessors used promises with pipelining for distributed objects. Futures came to mainstream libraries later: java.util.concurrent.Future in Java 5, std::future in C++11, Task in .NET 4, and concurrent.futures in Python 3.2. In JavaScript, libraries and the Promises/A+ community specification led to the Promise type of ECMAScript 2015.9 C#, JavaScript, Python, Rust and other languages then added async and await as syntax over their future types.
References
- ECMAScript Language Specification, Ecma International, 27.2 Promise Objects
- CompletableFuture, Java SE 25 API documentation, class description
- std::promise, cppreference.com, description
- std::future, cppreference.com, description
- Promise, MDN Web Docs, Description
- Futures, asyncio, Python 3.14 documentation, Future Object
- Future, Java SE 25 API documentation, interface description
- concurrent.futures, Python 3.14 documentation, Future Objects
- Promises/A+ specification, introduction
- Task-based asynchronous pattern (TAP), Microsoft Learn, Task status
- Trait Future, Rust standard library documentation, The poll method
- Futures and the Async Syntax, The Rust Programming Language, 17.1
- Composing suspending functions, Kotlin documentation, Concurrent using async
- std::async, cppreference.com, Notes
- The Incremental Garbage Collection of Processes, H. Baker and C. Hewitt, ACM SIGPLAN Notices 12(8), 1977, Introduction
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag EBXWXF Edit this page History Report an error Markdown