TypeScript 项目中的 Promise 全面解析
2025-06-04 01:52:11作者:魏献源Searcher
前言
在现代 JavaScript 开发中,Promise 已成为处理异步操作的核心工具。本文将深入探讨 Promise 的概念、优势以及在 TypeScript 中的实际应用,帮助开发者更好地理解和运用这一重要特性。
同步与异步的困境
同步代码的简洁性
我们先看一个同步读取 JSON 文件的例子:
import fs = require('fs');
function loadJSONSync(filename: string) {
return JSON.parse(fs.readFileSync(filename));
}
// 有效JSON文件
console.log(loadJSONSync('good.json'));
// 不存在的文件
try {
console.log(loadJSONSync('absent.json'));
} catch (err) {
console.log('absent.json error', err.message);
}
// 无效JSON文件
try {
console.log(loadJSONSync('invalid.json'));
} catch (err) {
console.log('invalid.json error', err.message);
}
这种同步方式简单直观,错误处理通过 try/catch 即可完成。
异步回调的复杂性
当我们尝试将其转换为异步版本时,问题开始显现:
import fs = require('fs');
function loadJSON(filename: string, cb: (error: Error, data: any) => void) {
fs.readFile(filename, function(err, data) {
if (err) cb(err);
else cb(null, JSON.parse(data));
});
}
这种实现存在严重问题:如果 JSON.parse 抛出错误,回调不会被调用,应用会崩溃。
Promise 的解决方案
Promise 基础
Promise 有三种状态:
- pending(等待中)
- fulfilled(已成功)
- rejected(已失败)
创建 Promise 的基本方式:
const promise = new Promise((resolve, reject) => {
// 使用 resolve/reject 控制 Promise 状态
});
结果处理
使用 .then 处理成功情况,.catch 处理失败情况:
Promise.resolve(123)
.then((res) => {
console.log(res); // 123
});
Promise.reject(new Error("错误"))
.catch((err) => {
console.log(err.message); // "错误"
});
Promise 链
Promise 的真正威力在于链式调用:
Promise.resolve(123)
.then((res) => {
console.log(res); // 123
return 456;
})
.then((res) => {
console.log(res); // 456
return Promise.resolve(789);
})
.then((res) => {
console.log(res); // 789
});
错误处理可以集中到一个 catch 中:
Promise.reject(new Error('错误'))
.then((res) => {
console.log(res); // 不会执行
return 456;
})
.catch((err) => {
console.log(err.message); // "错误"
});
TypeScript 中的 Promise
TypeScript 能智能推断 Promise 链中的类型:
Promise.resolve(123)
.then((res) => { // res 被推断为 number
return true; // 返回 boolean
})
.then((res) => { // res 被推断为 boolean
console.log(res);
});
对于返回 Promise 的函数,TypeScript 也能正确处理类型:
function delayedHello(): Promise<string> {
return new Promise((resolve) => {
setTimeout(() => resolve("Hello"), 1000);
});
}
Promise.resolve(123)
.then((res) => { // res 是 number
return delayedHello(); // 返回 Promise<string>
})
.then((res) => { // res 是 string
console.log(res); // "Hello"
});
实用技巧
回调函数转 Promise
将回调风格的函数转换为返回 Promise 的函数:
import fs = require('fs');
function readFileAsync(filename: string): Promise<any> {
return new Promise((resolve, reject) => {
fs.readFile(filename, (err, result) => {
if (err) reject(err);
else resolve(result);
});
});
}
JSON 示例的 Promise 实现
使用 Promise 重写 loadJSON 函数:
function loadJSONAsync(filename: string): Promise<any> {
return readFileAsync(filename)
.then((res) => JSON.parse(res));
}
使用示例:
loadJSONAsync('good.json')
.then((val) => console.log(val))
.catch((err) => console.log('error:', err.message));
并行控制
使用 Promise.all 处理并行任务:
// 串行执行,总时间约2秒
loadItem(1)
.then((item1) => loadItem(2))
.then((item2) => console.log('done'));
// 并行执行,总时间约1秒
Promise.all([loadItem(1), loadItem(2)])
.then(([item1, item2]) => console.log('done'));
使用 Promise.race 获取最先完成的结果:
Promise.race([task1, task2])
.then((value) => console.log(value)); // 输出先完成的任务结果
总结
Promise 为 JavaScript 异步编程带来了革命性的改进:
- 更清晰的代码结构
- 更直观的错误处理
- 更优雅的链式调用
- 更好的类型支持(在 TypeScript 中)
通过合理运用 Promise 及其相关方法,开发者可以编写出更健壮、更易维护的异步代码。TypeScript 的类型系统与 Promise 的结合,更是为大型应用开发提供了强有力的支持。
登录后查看全文
热门项目推荐
atomcodeClaude Code 的开源替代方案。连接任意大模型,编辑代码,运行命令,自动验证 — 全自动执行。用 Rust 构建,极致性能。 | An open-source alternative to Claude Code. Connect any LLM, edit code, run commands, and verify changes — autonomously. Built in Rust for speed. Get StartedRust067- DDeepSeek-V4-ProDeepSeek-V4-Pro(总参数 1.6 万亿,激活 49B)面向复杂推理和高级编程任务,在代码竞赛、数学推理、Agent 工作流等场景表现优异,性能接近国际前沿闭源模型。Python00
MiniMax-M2.7MiniMax-M2.7 是我们首个深度参与自身进化过程的模型。M2.7 具备构建复杂智能体应用框架的能力,能够借助智能体团队、复杂技能以及动态工具搜索,完成高度精细的生产力任务。Python00
GLM-5.1GLM-5.1是智谱迄今最智能的旗舰模型,也是目前全球最强的开源模型。GLM-5.1大大提高了代码能力,在完成长程任务方面提升尤为显著。和此前分钟级交互的模型不同,它能够在一次任务中独立、持续工作超过8小时,期间自主规划、执行、自我进化,最终交付完整的工程级成果。Jinja00
Kimi-K2.6Kimi K2.6 是一款开源的原生多模态智能体模型,在长程编码、编码驱动设计、主动自主执行以及群体任务编排等实用能力方面实现了显著提升。Python00
Hy3-previewHy3 preview 是由腾讯混元团队研发的2950亿参数混合专家(Mixture-of-Experts, MoE)模型,包含210亿激活参数和38亿MTP层参数。Hy3 preview是在我们重构的基础设施上训练的首款模型,也是目前发布的性能最强的模型。该模型在复杂推理、指令遵循、上下文学习、代码生成及智能体任务等方面均实现了显著提升。Python00
项目优选
收起
暂无描述
Dockerfile
687
4.45 K
Ascend Extension for PyTorch
Python
540
664
Claude Code 的开源替代方案。连接任意大模型,编辑代码,运行命令,自动验证 — 全自动执行。用 Rust 构建,极致性能。 | An open-source alternative to Claude Code. Connect any LLM, edit code, run commands, and verify changes — autonomously. Built in Rust for speed.
Get Started
Rust
379
66
openEuler内核是openEuler操作系统的核心,既是系统性能与稳定性的基石,也是连接处理器、设备与服务的桥梁。
C
406
322
本项目是CANN提供的数学类基础计算算子库,实现网络在NPU上加速计算。
C++
953
918
Oohos_react_native
React Native鸿蒙化仓库
C++
336
385
🎉 (RuoYi)官方仓库 基于SpringBoot,Spring Security,JWT,Vue3 & Vite、Element Plus 的前后端分离权限管理系统
Vue
1.58 K
923
暂无简介
Dart
935
234
华为昇腾面向大规模分布式训练的多模态大模型套件,支撑多模态生成、多模态理解。
Python
135
216
昇腾LLM分布式训练框架
Python
145
172