I. What Are Promise and Future
In synchronous programming, a function call usually has to wait for its result to return before execution can continue.
However, in scenarios such as network requests, file reads and writes, database queries, and remote service calls, a task may take a long time to complete. If the calling thread waits the whole time, the system's concurrency capacity and resource utilization will suffer.
Promise and Future are used to solve this problem.
They represent a computation that has not yet completed but may produce a result in the future.
1. The Basic Concept of Future
A Future represents a computation result that will only be completed in the future.
The caller can first obtain a Future object, then use that object to check the task status, wait for the task to complete, or retrieve the final result.
For example, in Java:
import java.util.concurrent.*;
public class FutureDemo {
public static void main(String[] args) throws Exception {
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<Integer> future = executor.submit(() -> {
Thread.sleep(1000);
return 100;
});
System.out.println("任务已提交");
Integer result = future.get();
System.out.println("结果:" + result);
executor.shutdown();
}
}
Execution process:
- Submit the task to the thread pool.
- Obtain the Future object.
- The main thread can continue performing other operations.
- Call
get()to wait for the result. - Retrieve the return value once the task completes.
Here, Future<Integer> represents a computational task that will produce an integer result in the future.
Note that a Future itself does not mean the task is necessarily executed asynchronously. The specific execution mode depends on the API and the executor that create the Future.
2. The Basic Concept of Promise
A Promise represents a commitment to the final result of an asynchronous operation.
Compared with a traditional Future, a Promise usually provides the ability to actively complete the task.
The caller or the task executor can:
- Mark the Promise as successful.
- Mark the Promise as failed.
- Pass the result on to subsequent operations that depend on it.
- Register handling logic for success or failure.
For example, in JavaScript:
const promise = new Promise((resolve, reject) => {
const success = true;
if (success) {
resolve(100);
} else {
reject(new Error("任务失败"));
}
});
promise
.then(result => {
console.log("结果:", result);
})
.catch(error => {
console.error(error);
});
Where:
resolveis used to fulfill the Promise.rejectis used to complete the Promise in a failed state.thenregisters the handling logic for success.catchregisters the handling logic for failure.
3. The Relationship Between Promise and Future
The definitions of Promise and Future are not entirely consistent across different languages.
From an abstract perspective:
| Concept | Core responsibility |
|---|---|
| Future | Represents a computation result that may be obtained in the future |
| Promise | Provides the ability to complete a future result |
| Future | Usually created by the task executor and handed to the caller |
| Promise | Usually held by the task producer and responsible for completion |
| Promise | In many designs, can expose the corresponding Future |
In some languages and frameworks, Promise and Future are two different interfaces; in others, Promise is the asynchronous result object itself.
For example:
- Java:
FutureandCompletableFuture. - JavaScript: mainly uses
Promise. - Python:
concurrent.futures.Futureandasyncio.Future. - Scala:
FutureandPromiseare separate. - Rust: asynchronous computation is represented via the Future Trait, and the underlying task completion mechanism is provided by the executor and the specific implementation.
Therefore, Promise and Future in different languages cannot be regarded as exactly the same API.
II. Why Promise and Future Are Needed
Traditional callback functions can implement asynchronous operations, but in complex business logic they easily lead to problems with control flow and error handling.
1. The Problems with Traditional Callbacks
For example, execute three dependent tasks in sequence:
getUser(userId, (user) => {
getOrders(user.id, (orders) => {
getOrderDetail(orders[0].id, (detail) => {
getProduct(detail.productId, (product) => {
console.log(product);
});
});
});
});
This structure has several problems:
- Callback nesting is deep.
- Error handling is scattered.
- Dependencies among multiple tasks are not intuitive.
- Code reuse is difficult.
- Composing concurrent tasks is complex.
2. Promise Improvements
A Promise encapsulates the result of an asynchronous operation in an object.
Callers no longer need to keep nesting inside every callback; instead, they express task dependencies through chained calls.
getUser(userId)
.then(user => getOrders(user.id))
.then(orders => getOrderDetail(orders[0].id))
.then(detail => getProduct(detail.productId))
.then(product => {
console.log(product);
})
.catch(error => {
console.error(error);
});
This approach organizes tasks into a continuous asynchronous processing chain.
3. Core Design Value
| Design Goal | Description |
|---|---|
| Result abstraction | Encapsulate a future result as an object |
| State management | Manage task completion states uniformly |
| Error propagation | Propagate asynchronous failure information uniformly |
| Chained composition | Connect multiple asynchronous tasks together |
| Concurrent composition | Support parallel execution and result aggregation of multiple tasks |
| Separation of control flow | Separate task execution from result handling |
III. Promise State Model
Promises typically use a finite-state model to describe the lifecycle of asynchronous operations.
JavaScript Promises define three states:
| State | Meaning | Whether Further Transition Is Possible |
|---|---|---|
| Pending | Waiting | Yes |
| Fulfilled | Completed successfully | No |
| Rejected | Failed | No |
1. Pending State
Pending means the asynchronous task has not yet completed.
const promise = new Promise((resolve, reject) => {
// Do not call resolve or reject for now
});
At this point, the Promise is still in a pending state.
2. Fulfilled State
Fulfilled means the task completed successfully and produced a result value.
const promise = Promise.resolve(100);
After the Promise completes successfully, the result can be obtained via then.
3. Rejected State
Rejected means task execution failed and produced a rejection reason.
const promise = Promise.reject(
new Error("网络请求失败")
);
The failure reason can be handled via catch or the second argument of then.
4. Promise State Transitions
flowchart TD
A["Pending"] --> B{"Task completion result"}
B -->|"Success"| C["Fulfilled"]
B -->|"Failure"| D["Rejected"]
C --> E["State determined"]
D --> E
E --> F["Execute the corresponding handling logic"]
style A fill:#FFF5DE,stroke:#E8D29A,color:#334155
style B fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style C fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style D fill:#FBE9E9,stroke:#D9AAAA,color:#334155
style E fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style F fill:#E8EDF2,stroke:#B8C3CE,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
5. State Is Irreversible
One of the most important constraints of a Promise is that its state can be determined only once.
const promise = new Promise((resolve, reject) => {
resolve("成功");
reject("失败");
});
The final state is Fulfilled; the subsequent reject does not change the state that has already been determined.
Likewise:
const promise = new Promise((resolve, reject) => {
reject("失败");
resolve("成功");
});
The final state is Rejected.
Two concepts need to be distinguished:
- The state of a Promise (State): Pending, Fulfilled, Rejected.
- The fate of a Promise (Fate): whether it has already been resolved or locked to the result of another Promise.
In the JavaScript specification, once a Promise is resolved or rejected, it cannot be resolved again. In particular, when resolve receives another Promise or thenable, the outer Promise may still be in the Pending state, but its final result is already constrained by that object.
IV. Core Execution Mechanism of Promise
A Promise is not just an object that stores a result; it also includes result propagation, handler registration, and task scheduling mechanisms.
1. Creating a Promise
JavaScript:
const promise = new Promise((resolve, reject) => {
const result = 100;
if (result > 0) {
resolve(result);
} else {
reject(new Error("结果无效"));
}
});
The constructor receives an executor function (Executor).
The executor has two parameters:
| Parameter | Purpose |
|---|---|
| resolve | Resolves the Promise to a successful result or follows another result |
| reject | Ends the Promise in a failed state |
A detail that is easy to overlook:
The executor function of a JavaScript Promise is executed synchronously when the Promise is created.
console.log("开始");
const promise = new Promise((resolve) => {
console.log("执行器");
resolve(100);
});
console.log("结束");
Output:
开始
执行器
结束
A Promise does not automatically place the executor on a background thread.
2. Registering Handler Functions
A Promise can register a fulfillment handler via then.
Promise.resolve(100).then(result => {
console.log(result);
});
then accepts two optional parameters:
promise.then(onFulfilled, onRejected);
Where:
onFulfilled: the fulfillment handler.onRejected: the rejection handler.
catch is a common way to register a rejection handler:
promise.catch(error => {
console.error(error);
});
finally is used to register cleanup logic that must run regardless of success or failure:
promise.finally(() => {
console.log("任务处理结束");
});
finally usually does not receive the original fulfillment value or rejection reason, nor does it change the original result by default; however, if the finally callback throws an exception or returns a rejected Promise, the subsequent chain becomes rejected.
3. Return value of then
then returns a new Promise.
This is the foundation of Promise chaining.
const promise1 = Promise.resolve(10);
const promise2 = promise1.then(value => {
return value * 2;
});
promise2.then(value => {
console.log(value);
});
The result is:
20
Its core rules are:
| Callback behavior | Result of the new Promise |
|---|---|
| Returns a normal value | Fulfills, with the returned value as its value |
| Returns a Promise | Adopts that Promise's final state and result |
| Throws an exception | Rejects with the exception as the reason |
| Returns a thenable | Adopts the thenable's final state and result |
| No fulfillment handler | Passes through the original fulfillment value |
| No rejection handler | Passes through the original rejection reason |
For example:
Promise.resolve(10)
.then(value => {
return Promise.resolve(value + 5);
})
.then(value => {
console.log(value);
});
Output:
15
4. Execution flow of a Promise chain
flowchart TD
A["Create Promise"] --> B["Executor runs"]
B --> C{"Task result"}
C -->|"Success"| D["Fulfilled"]
C -->|"Failure"| E["Rejected"]
D --> F["Schedule fulfillment handler"]
E --> G["Schedule rejection handler"]
F --> H["Create a new Promise"]
G --> H
H --> I{"Handler result"}
I -->|"Normal value"| J["New Promise fulfills"]
I -->|"Promise or thenable"| K["Adopt its final state"]
I -->|"Throws exception"| L["New Promise rejects"]
J --> M["Continue the subsequent chain"]
K --> M
L --> M
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style C fill:#FFF5DE,stroke:#E8D29A,color:#334155
style D fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style E fill:#FBE9E9,stroke:#D9AAAA,color:#334155
style F fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style G fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style H fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style I fill:#FFF5DE,stroke:#E8D29A,color:#334155
style J fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style K fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style L fill:#FBE9E9,stroke:#D9AAAA,color:#334155
style M fill:#E8EDF2,stroke:#B8C3CE,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
V. Promise Microtask Scheduling Mechanism
In JavaScript, Promise handlers are not executed immediately when registered; they are scheduled through the microtask mechanism.
Understanding microtasks is the key to mastering Promise execution order.
1. Synchronous and asynchronous tasks
Common task types in the JavaScript execution environment include:
| Type | Example | Execution characteristics |
|---|---|---|
| Synchronous task | An ordinary function call | Enters the current call stack immediately |
| Microtask | A Promise's then callback | Runs after the current call stack is cleared |
| Macrotask | Timer callbacks, some event tasks | Scheduled by the event loop |
Here, "macrotask" is a common teaching and engineering term. The HTML specification more precisely uses task to describe the task queue, and different runtimes have their own rules about task sources and scheduling details.
2. Why Promise callbacks are not executed immediately
console.log("1");
Promise.resolve().then(() => {
console.log("2");
});
console.log("3");
Output:
1
3
2
The reason:
- Synchronous code runs, printing 1.
- The Promise handler is registered and scheduled as a microtask.
- Synchronous code continues, printing 3.
- The current call stack is cleared.
- The microtask runs, printing 2.
3. Microtask execution order
console.log("A");
setTimeout(() => {
console.log("B");
}, 0);
Promise.resolve().then(() => {
console.log("C");
});
console.log("D");
Output:
A
D
C
B
In the common case of the browser's standard event loop, once the current task ends, the microtask checkpoint runs first, and only then does the next task begin.
4. Microtask scheduling flow
flowchart TD
A["Run the current task"] --> B["Execute synchronous code"]
B --> C["Register the Promise handler"]
C --> D["The microtask enters the queue"]
D --> E["The current call stack is cleared"]
E --> F["Run the microtask queue"]
F --> G{"Is a new microtask produced?"}
G -->|"Yes"| F
G -->|"No"| H["Proceed to the next event loop task"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
style E fill:#E8EDF2,stroke:#B8C3CE,color:#334155
style F fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style G fill:#FFF5DE,stroke:#E8D29A,color:#334155
style H fill:#E5F4EC,stroke:#A3CBB5,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
Things to note:
- A Promise's
thencallback is a microtask. - A Promise's executor runs synchronously.
- New microtasks can be produced while microtasks are executing.
- The microtask queue is usually processed continuously before the next task begins.
- A large number of microtasks can keep other tasks from being scheduled for a long time.
5. The difference between microtasks and asynchronous I/O
A Promise itself does not perform network requests, disk reads or writes, or create threads.
For example:
fetch("/api/users")
.then(response => response.json())
.then(data => {
console.log(data);
});
Several distinct layers are involved here:
fetchinitiates the network request.- The browser runtime and the underlying networking machinery handle the I/O.
- When the request completes, the Promise is resolved.
- The
thencallback enters the microtask scheduling flow. - JavaScript executes the callback and processes the data.
So a Promise is an abstraction over asynchronous results and control flow; it is not the same as the underlying asynchronous execution engine.
VI. How Futures execute and how results are obtained
Futures are designed differently in different languages; in particular, it is important to distinguish blocking Futures from lazy Futures.
1. Java Future
Java Future mainly represents the result of an asynchronous computation task.
Common methods:
| Method | Purpose |
|---|---|
get() |
Wait for the task to complete and retrieve the result |
get(timeout, unit) |
Wait for the result with a timeout |
isDone() |
Determine whether the task is completed |
isCancelled() |
Determine whether the task is cancelled |
cancel() |
Attempt to cancel the task |
Example:
import java.util.concurrent.*;
public class FutureExample {
public static void main(String[] args) throws Exception {
ExecutorService executor =
Executors.newFixedThreadPool(2);
Future<String> future = executor.submit(() -> {
Thread.sleep(1000);
return "任务完成";
});
System.out.println(future.isDone());
String result = future.get();
System.out.println(result);
executor.shutdown();
}
}
get() is a blocking result-retrieval operation.
If the task has not yet completed, the calling thread will wait.
Therefore, the existence of Future does not mean that the caller will not block.
2. Limitations of Java Future
Traditional Java Future has the following shortcomings:
get()may block the calling thread.- Does not support directly registering a complete result-processing chain.
- Combining multiple Futures is not convenient enough.
- Exception handling requires explicitly handling
ExecutionException. - Dependencies between tasks are not intuitive enough.
For example:
Future<Integer> future = executor.submit(() -> 100);
Integer result = future.get();
After calling get(), the current thread must wait for the result.
3. CompletableFuture
Java 8 introduced CompletableFuture, providing richer asynchronous composition capabilities.
import java.util.concurrent.*;
public class CompletableFutureDemo {
public static void main(String[] args) {
CompletableFuture.supplyAsync(() -> 100)
.thenApply(value -> value * 2)
.thenAccept(System.out::println)
.exceptionally(error -> {
error.printStackTrace();
return null;
});
}
}
Common methods:
| Method | Purpose |
|---|---|
supplyAsync() |
Asynchronously execute a task with a return value |
runAsync() |
Asynchronously execute a task without a return value |
thenApply() |
Transform the result of the previous step |
thenAccept() |
Consume the result of the previous step |
thenRun() |
Execute a subsequent action after the previous step completes |
thenCompose() |
Chain another asynchronous task |
thenCombine() |
Combine the results of two independent tasks |
allOf() |
Wait for all tasks to complete |
anyOf() |
Wait for any one task to complete |
exceptionally() |
Handle exceptions and provide a recovery result |
handle() |
Handle both success and failure |
whenComplete() |
Observe the success or failure result |
4. thenApply and thenCompose
These are two methods in Java CompletableFuture that are very easy to confuse.
thenApply is used to transform the result synchronously.
CompletableFuture<Integer> future =
CompletableFuture.supplyAsync(() -> 10)
.thenApply(value -> value * 2);
Result type:
CompletableFuture<Integer>
thenCompose is used to chain another asynchronous computation, avoiding nested Futures.
CompletableFuture<String> future =
CompletableFuture.supplyAsync(() -> 10)
.thenCompose(id ->
CompletableFuture.supplyAsync(() -> "用户:" + id)
);
The difference between the two:
| Method | Input | Returns | Typical use |
|---|---|---|---|
| thenApply | T | U | Normal result transformation |
| thenCompose | T | CompletionStage | Chaining asynchronous tasks |
If you use thenApply to return another Future, the result may become a nested structure:
CompletableFuture<CompletableFuture<String>>
Using thenCompose, however, can flatten it to:
CompletableFuture<String>
5. Future and Executors
Future usually needs to be used together with an executor.
Common executors in Java:
ExecutorExecutorServiceForkJoinPoolScheduledExecutorService
The executor is responsible for task scheduling, and Future is responsible for representing the task result.
Their responsibilities differ:
| Component | Responsibility |
|---|---|
| Executor | Receives and schedules tasks |
| Thread pool | Manages worker threads |
| Future | Represents the future result of a task |
| CompletableFuture | Provides asynchronous result composition and completion control |
VII. Promise and Future in Different Languages
1. JavaScript: Promise
JavaScript uses Promise as the standard abstraction for asynchronous results.
Main features:
- Three-state model.
thenchaining.catcherror propagation.finallycleanup operations.- Microtask scheduling.
- Supports Promise composition.
Common composition methods:
| Method | Behavior |
|---|---|
Promise.all() |
Succeeds only if all succeed; if any one rejects, the whole rejects |
Promise.allSettled() |
Waits for all to complete, preserving each result's status |
Promise.race() |
Uses the Promise that settles first |
Promise.any() |
The first successful Promise determines the result; rejects only if all fail |
Promise.resolve() |
Creates an already resolved Promise |
Promise.reject() |
Creates an already rejected Promise |
2. Python: concurrent.futures.Future
The Python standard library provides concurrent.futures.Future, used to represent the execution result of a thread pool or process pool task.
from concurrent.futures import ThreadPoolExecutor
def calculate():
return 100
with ThreadPoolExecutor() as executor:
future = executor.submit(calculate)
print(future.done())
print(future.result())
Common methods:
| Method | Purpose |
|---|---|
result() |
Waits for the task to complete and gets the result |
done() |
Determines whether it is completed |
cancel() |
Attempts to cancel the task |
exception() |
Gets the exception |
add_done_callback() |
Registers a task completion callback |
Python's concurrent.futures.Future is mainly intended for thread pool and process pool tasks and should not be confused with asyncio.Future.
3. Python: asyncio.Future
asyncio.Future is used to represent an asynchronous result in the event loop.
import asyncio
async def main():
future = asyncio.get_running_loop().create_future()
asyncio.get_running_loop().call_later(
1,
future.set_result,
100
)
result = await future
print(result)
asyncio.run(main())
Main features:
- Works with the event loop.
- The result can be awaited via
await. - Supports success, failure, and cancellation states.
- Usually not a thread-safe object.
- Cannot be mixed directly with
concurrent.futures.Future.
4. Scala: Future and Promise
Scala separates Future and Promise:
- Future: a read-only future result.
- Promise: a writable side that can actively complete the result.
Example:
import scala.concurrent._
import scala.concurrent.ExecutionContext.Implicits.global
val future = Future {
100
}
future.foreach { result =>
println(result)
}
A Promise can be used to actively complete:
val promise = Promise[Int]()
val future = promise.future
promise.success(100)
This design reflects the separation of responsibilities between producer and consumer.
5. Rust: Future Trait
Rust's Future is an abstraction for asynchronous computation.
use std::future::Future;
async fn calculate() -> i32 {
100
}
fn accept_future<F: Future<Output = i32>>(_: F) {}