返回专栏
· 24 分钟阅读

Promise 与 Future


一、什么是 Promise 与 Future

在同步编程中,函数调用通常需要等待结果返回后才能继续执行。

但在网络请求、文件读写、数据库查询和远程服务调用等场景中,任务可能需要较长时间才能完成。如果调用线程一直等待,会降低系统的并发能力和资源利用率。

Promise 与 Future 用于解决这一问题。

它们代表一个尚未完成、但未来可能产生结果的计算过程。

1. Future 的基本概念

Future 表示一个未来才会完成的计算结果。

调用方可以先获得 Future 对象,再通过该对象检查任务状态、等待任务完成或获取最终结果。

例如 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();
    }
}

执行过程:

  1. 向线程池提交任务。
  2. 获取 Future 对象。
  3. 主线程可以继续执行其他操作。
  4. 调用 get() 等待结果。
  5. 任务完成后获取返回值。

这里的 Future<Integer> 表示一个未来会产生整数结果的计算任务。

需要注意:Future 本身并不意味着任务一定异步执行。具体执行方式取决于创建 Future 的 API 和执行器。

2. Promise 的基本概念

Promise 表示一个异步操作的最终结果承诺。

与传统 Future 相比,Promise 通常提供主动完成任务的能力。

调用方或任务执行方可以:

  • 将 Promise 标记为成功。
  • 将 Promise 标记为失败。
  • 将结果传递给依赖该结果的后续操作。
  • 注册成功或失败后的处理逻辑。

例如 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);
    });

其中:

  • resolve 用于完成 Promise。
  • reject 用于以失败状态完成 Promise。
  • then 注册成功后的处理逻辑。
  • catch 注册失败后的处理逻辑。

3. Promise 与 Future 的关系

Promise 和 Future 在不同语言中的定义并不完全一致。

从抽象层面看:

概念 核心职责
Future 表示未来可能获得的计算结果
Promise 提供完成未来结果的能力
Future 通常由任务执行方创建并交给调用方
Promise 通常由任务生产方持有并负责完成
Promise 在很多设计中可以暴露对应的 Future

在一些语言和框架中,Promise 与 Future 是两个不同的接口;在另一些语言中,Promise 是异步结果对象本身。

例如:

  • Java:Future 和 CompletableFuture。
  • JavaScript:主要使用 Promise。
  • Python:concurrent.futures.Future 和 asyncio.Future。
  • Scala:Future 和 Promise 分离。
  • Rust:通过 Future Trait 表示异步计算,底层任务完成机制由执行器和具体实现提供。

因此,不能将不同语言中的 Promise 与 Future 视为完全相同的 API。


二、为什么需要 Promise 与 Future

传统回调函数可以实现异步操作,但在复杂业务中容易产生控制流和错误处理问题。

1. 传统回调的问题

例如,依次执行三个依赖任务:

getUser(userId, (user) => {
    getOrders(user.id, (orders) => {
        getOrderDetail(orders[0].id, (detail) => {
            getProduct(detail.productId, (product) => {
                console.log(product);
            });
        });
    });
});

这种结构存在几个问题:

  • 回调嵌套层级较深。
  • 错误处理分散。
  • 多个任务的依赖关系不直观。
  • 代码复用困难。
  • 并发任务组合复杂。

2. Promise 的改进

Promise 将异步操作的结果封装成对象。

调用方不必在每个回调中继续嵌套,而是通过链式调用表达任务依赖关系。

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);
    });

这种方式将任务组织成连续的异步处理链。

3. 核心设计价值

设计目标 说明
结果抽象 将未来结果封装为对象
状态管理 统一管理任务完成状态
错误传播 统一传递异步失败信息
链式组合 将多个异步任务连接起来
并发组合 支持多个任务并行执行及结果汇总
控制流分离 将任务执行与结果处理分离

三、Promise 的状态模型

Promise 通常采用有限状态模型描述异步操作的生命周期。

JavaScript Promise 定义了三种状态:

状态 含义 是否可继续转换
Pending 等待中 可以
Fulfilled 已成功完成 不可以
Rejected 已失败 不可以

1. Pending 状态

Pending 表示异步任务尚未完成。

const promise = new Promise((resolve, reject) => {
    // 暂时不调用 resolve 或 reject
});

此时 Promise 仍处于等待状态。

2. Fulfilled 状态

Fulfilled 表示任务成功完成,并产生结果值。

const promise = Promise.resolve(100);

Promise 成功完成后,可以通过 then 获取结果。

3. Rejected 状态

Rejected 表示任务执行失败,并产生拒绝原因。

const promise = Promise.reject(
    new Error("网络请求失败")
);

失败原因可以通过 catch 或 then 的第二个参数处理。

4. Promise 状态转换

flowchart TD
    A["Pending"] --> B{"任务完成结果"}
    B -->|"成功"| C["Fulfilled"]
    B -->|"失败"| D["Rejected"]
    C --> E["状态确定"]
    D --> E
    E --> F["执行对应处理逻辑"]

    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. 状态不可逆

Promise 最重要的约束之一是状态只能确定一次。

const promise = new Promise((resolve, reject) => {
    resolve("成功");
    reject("失败");
});

最终状态为 Fulfilled,后续的 reject 不会改变已经确定的状态。

同样:

const promise = new Promise((resolve, reject) => {
    reject("失败");
    resolve("成功");
});

最终状态为 Rejected。

需要区分两个概念:

  • Promise 的状态(State):Pending、Fulfilled、Rejected。
  • Promise 的命运(Fate):是否已经被解决或锁定到另一个 Promise 的结果。

在 JavaScript 规范中,Promise 一旦被 resolve 或 reject,就不能再被重新解决。尤其是 resolve 接收另一个 Promise 或 thenable 时,外层 Promise 可能仍然处于 Pending 状态,但其最终结果已经受到该对象约束。


四、Promise 的核心执行机制

Promise 不只是一个保存结果的对象,还包含结果传递、处理函数注册和任务调度机制。

1. 创建 Promise

JavaScript:

const promise = new Promise((resolve, reject) => {
    const result = 100;

    if (result > 0) {
        resolve(result);
    } else {
        reject(new Error("结果无效"));
    }
});

构造函数接收一个执行器函数(Executor)。

执行器具有两个参数:

参数 作用
resolve 将 Promise 解决为成功结果或跟随其他结果
reject 将 Promise 以失败状态结束

一个容易忽略的细节:

JavaScript Promise 的执行器函数会在创建 Promise 时同步执行。

console.log("开始");

const promise = new Promise((resolve) => {
    console.log("执行器");
    resolve(100);
});

console.log("结束");

输出:

开始
执行器
结束

Promise 并不会自动将执行器放到后台线程中。

2. 注册处理函数

Promise 可以通过 then 注册成功处理函数。

Promise.resolve(100).then(result => {
    console.log(result);
});

then 接收两个可选参数:

promise.then(onFulfilled, onRejected);

其中:

  • onFulfilled:成功处理函数。
  • onRejected:失败处理函数。

catch 是注册失败处理函数的常用方式:

promise.catch(error => {
    console.error(error);
});

finally 用于注册无论成功还是失败都需要执行的收尾逻辑:

promise.finally(() => {
    console.log("任务处理结束");
});

finally 通常不接收原始成功值或失败原因,也不会默认改变原有结果;但如果 finally 回调抛出异常或返回拒绝的 Promise,后续链会变为拒绝状态。

3. then 的返回值

then 会返回一个新的 Promise。

这是 Promise 链式调用的基础。

const promise1 = Promise.resolve(10);

const promise2 = promise1.then(value => {
    return value * 2;
});

promise2.then(value => {
    console.log(value);
});

结果为:

20

其核心规则:

回调行为 新 Promise 的结果
返回普通值 成功完成,值为返回值
返回 Promise 采用该 Promise 的最终状态和结果
抛出异常 以异常作为拒绝原因
返回 thenable 采用 thenable 的最终状态和结果
没有成功处理函数 透传原成功值
没有失败处理函数 透传原拒绝原因

例如:

Promise.resolve(10)
    .then(value => {
        return Promise.resolve(value + 5);
    })
    .then(value => {
        console.log(value);
    });

输出:

15

4. Promise 链的执行流程

flowchart TD
    A["创建 Promise"] --> B["执行器运行"]
    B --> C{"任务结果"}
    C -->|"成功"| D["Fulfilled"]
    C -->|"失败"| E["Rejected"]
    D --> F["调度成功处理函数"]
    E --> G["调度失败处理函数"]
    F --> H["生成新的 Promise"]
    G --> H
    H --> I{"处理函数结果"}
    I -->|"普通值"| J["新 Promise 成功"]
    I -->|"Promise 或 thenable"| K["采用其最终状态"]
    I -->|"抛出异常"| L["新 Promise 失败"]
    J --> M["继续后续链"]
    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

五、Promise 的微任务调度机制

在 JavaScript 中,Promise 的处理函数并不是在注册时立即执行,而是通过微任务机制安排执行。

理解微任务是掌握 Promise 执行顺序的关键。

1. 同步任务与异步任务

JavaScript 执行环境中常见的任务类型包括:

类型 示例 执行特点
同步任务 普通函数调用 立即进入当前调用栈
微任务 Promise 的 then 回调 当前调用栈清空后执行
宏任务 定时器回调、部分事件任务 由事件循环调度

这里的“宏任务”是常见教学和工程术语。HTML 规范更具体地使用 task 表述任务队列,不同运行时对任务来源和调度细节有各自规定。

2. Promise 回调为什么不是立即执行

console.log("1");

Promise.resolve().then(() => {
    console.log("2");
});

console.log("3");

输出:

1
3
2

原因:

  1. 执行同步代码,输出 1。
  2. 注册 Promise 处理函数,将其安排为微任务。
  3. 继续执行同步代码,输出 3。
  4. 当前调用栈清空。
  5. 执行微任务,输出 2。

3. 微任务执行顺序

console.log("A");

setTimeout(() => {
    console.log("B");
}, 0);

Promise.resolve().then(() => {
    console.log("C");
});

console.log("D");

输出:

A
D
C
B

在浏览器标准事件循环的常见场景中,当前任务结束后会先执行微任务检查点,再开始后续任务。

4. 微任务调度流程

flowchart TD
    A["执行当前任务"] --> B["运行同步代码"]
    B --> C["注册 Promise 处理函数"]
    C --> D["微任务进入队列"]
    D --> E["当前调用栈清空"]
    E --> F["执行微任务队列"]
    F --> G{"是否产生新微任务"}
    G -->|"是"| F
    G -->|"否"| H["进入后续事件循环任务"]

    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

需要注意:

  • Promise 的 then 回调属于微任务。
  • Promise 的执行器是同步执行的。
  • 微任务执行过程中可以继续产生新的微任务。
  • 微任务队列通常会在进入后续任务前持续处理。
  • 大量微任务可能导致其他任务长时间得不到调度。

5. 微任务与异步 I/O 的区别

Promise 本身不负责执行网络请求、磁盘读写或创建线程。

例如:

fetch("/api/users")
    .then(response => response.json())
    .then(data => {
        console.log(data);
    });

这里涉及不同层次:

  1. fetch 发起网络请求。
  2. 浏览器运行时和底层网络机制处理 I/O。
  3. 请求结果完成后,Promise 被解决。
  4. then 回调进入微任务调度流程。
  5. JavaScript 执行回调并处理数据。

因此,Promise 是异步结果与控制流抽象,不等于底层异步执行引擎。


六、Future 的执行与获取机制

Future 在不同语言中有不同的设计,尤其需要区分阻塞式 Future 和惰性 Future。

1. Java Future

Java Future 主要表示一个异步计算任务的结果。

常用方法:

方法 作用
get() 等待任务完成并获取结果
get(timeout, unit) 限时等待结果
isDone() 判断任务是否完成
isCancelled() 判断任务是否取消
cancel() 尝试取消任务

示例:

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() 是阻塞式结果获取操作。

如果任务尚未完成,调用线程会等待。

因此,Future 的存在并不意味着调用方不会阻塞。

2. Java Future 的局限

传统 Java Future 具有以下不足:

  • get() 可能阻塞调用线程。
  • 不支持直接注册完整的结果处理链。
  • 多个 Future 的组合不够方便。
  • 异常处理需要显式处理 ExecutionException。
  • 任务之间的依赖关系不够直观。

例如:

Future<Integer> future = executor.submit(() -> 100);

Integer result = future.get();

调用 get() 后,当前线程必须等待结果。

3. CompletableFuture

Java 8 引入 CompletableFuture,提供了更丰富的异步组合能力。

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;
            });
    }
}

常用方法:

方法 作用
supplyAsync() 异步执行有返回值的任务
runAsync() 异步执行无返回值的任务
thenApply() 转换上一步结果
thenAccept() 消费上一步结果
thenRun() 上一步完成后执行后续动作
thenCompose() 串联另一个异步任务
thenCombine() 合并两个独立任务的结果
allOf() 等待多个任务全部完成
anyOf() 等待任意一个任务完成
exceptionally() 处理异常并提供恢复结果
handle() 同时处理成功和失败
whenComplete() 观察成功或失败结果

4. thenApply 与 thenCompose

这是 Java CompletableFuture 中非常容易混淆的两个方法。

thenApply 用于同步转换结果。

CompletableFuture<Integer> future =
    CompletableFuture.supplyAsync(() -> 10)
        .thenApply(value -> value * 2);

结果类型:

CompletableFuture<Integer>

thenCompose 用于连接另一个异步计算,避免嵌套 Future。

CompletableFuture<String> future =
    CompletableFuture.supplyAsync(() -> 10)
        .thenCompose(id ->
            CompletableFuture.supplyAsync(() -> "用户:" + id)
        );

两者区别:

方法 输入 返回 典型用途
thenApply T U 普通结果转换
thenCompose T CompletionStage 异步任务串联

如果使用 thenApply 返回另一个 Future,结果可能变成嵌套结构:

CompletableFuture<CompletableFuture<String>>

使用 thenCompose 则可以将其扁平化为:

CompletableFuture<String>

5. Future 与执行器

Future 通常需要与执行器配合使用。

Java 中常见的执行器:

  • Executor
  • ExecutorService
  • ForkJoinPool
  • ScheduledExecutorService

执行器负责任务调度,Future 负责表示任务结果。

两者职责不同:

组件 职责
Executor 接收并调度任务
线程池 管理工作线程
Future 表示任务的未来结果
CompletableFuture 提供异步结果组合与完成控制

七、不同语言中的 Promise 与 Future

1. JavaScript:Promise

JavaScript 使用 Promise 作为标准异步结果抽象。

主要特征:

  • 三态模型。
  • then 链式处理。
  • catch 错误传播。
  • finally 清理操作。
  • 微任务调度。
  • 支持 Promise 组合。

常用组合方法:

方法 行为
Promise.all() 全部成功才成功,任意一个拒绝则整体拒绝
Promise.allSettled() 等待全部完成,保留每个结果状态
Promise.race() 采用最先确定状态的 Promise
Promise.any() 第一个成功的 Promise 决定结果,全部失败才拒绝
Promise.resolve() 创建已解决的 Promise
Promise.reject() 创建已拒绝的 Promise

2. Python:concurrent.futures.Future

Python 标准库提供 concurrent.futures.Future,用于表示线程池或进程池任务的执行结果。

from concurrent.futures import ThreadPoolExecutor
def calculate():
    return 100
with ThreadPoolExecutor() as executor:
    future = executor.submit(calculate)
print(future.done())
    print(future.result())

常见方法:

方法 作用
result() 等待任务完成并获取结果
done() 判断是否完成
cancel() 尝试取消任务
exception() 获取异常
add_done_callback() 注册任务完成回调

Python 的 concurrent.futures.Future 主要面向线程池和进程池任务,不应与 asyncio.Future 混淆。

3. Python:asyncio.Future

asyncio.Future 用于表示事件循环中的异步结果。

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())

主要特征:

  • 与事件循环协作。
  • 可以通过 await 等待结果。
  • 支持成功、失败和取消状态。
  • 通常不是线程安全对象。
  • 不能直接与 concurrent.futures.Future 混用。

4. Scala:Future 与 Promise

Scala 将 Future 和 Promise 分离:

  • Future:只读的未来结果。
  • Promise:可以主动完成结果的写入端。

示例:

import scala.concurrent._
import scala.concurrent.ExecutionContext.Implicits.global
val future = Future {
  100
}
future.foreach { result =>
  println(result)
}

通过 Promise 可以主动完成:

val promise = Promise[Int]()
val future = promise.future
promise.success(100)

这种设计体现了生产者和消费者之间的职责分离。

5. Rust:Future Trait

Rust 的 Future 是一种异步计算抽象。

use std::future::Future;
async fn calculate() -> i32 {
    100
}
fn accept_future<F: Future<Output = i32>>(_: F) {}