Promise通过链式调用实现异步流程控制,每个then返回新Promise,值按规则传递;catch处理前序错误但需末尾兜底;Promise.all等待所有成功,race取最快结果;可封装重试机制提升容错,核心在于状态流转与组合能力。
JavaScript中的Promise不只是解决回调地狱的工具,掌握其深层机制和高级用法,能让你更从容地处理复杂异步场景。真正理解Promise,意味着你不仅能写异步代码,还能写出可维护、可调试、健壮的逻辑。
每个then方法都会返回一个新的Promise,这使得链式调用成为可能。关键在于返回值如何被下一个then接收:
示例:
Promise.resolve(1) .then(x => x + 1) .then(x => Promise.resolve(x * 2)) .then(console.log); // 输出 4
catch本质上是then(null, rejectionCallback)的语法糖。常见误区是认为catch能捕获整个链路上的所有错误,但其实它只捕获前面未被处理的拒绝状态。
避免漏掉错误:
fetch('/api/data')
.then(res => res.json())
.then(data => { throw new Error('处理失败') })
.catch(err => console.error('出错了:', err));
面对多个异步任务,你需要根据场景选择合适的并发策略。
Promise.all:超时示例:
const timeout = new Promise((_, reject) =>
setTimeout(() => reject(new Error('请求超时')), 5000)
);
Promise.race([fetch('/api/data'), timeout])
.then(res => console.log('成功'))
.catch(err => console.error(err.message));
网络请求不稳定时,自动重试能提升用户体验。基于Promise可以轻松实现可控的重试逻辑。
function retry(fn, retries = 3) { return new Promise((resolve, reject) => { function attempt() { fn() .then(resolve) .catch(err => { if (retries > 0) { retries--; setTimeout(attempt, 1000); } else { reject(err); } }); } attempt(); }); }
// 使用 retry(() => fetch('/api/data')).then(...);
这个模式可以扩展加入指数退避、错误类型判断等策略。
基本上就这些。Promise的强大之处在于组合能力,理解其状态流转和链式规则后,你可以构建出灵活可靠的异步流程。不复杂但容易忽略细节。