Promise是JavaScript处理异步操作的标准容器,用于解决回调嵌套问题;适用于需串行执行多个有依赖的异步任务,且是理解async/await的前提。
Promise 不是语法糖,也不是替代回调的“新写法”,它是 JavaScript 中处理异步操作的标准化容器。当你需要串行执行多个异步任务(比如先 fetch 用户数据,再用 ID 去查订单),又不想陷入回调嵌套(callback hell),Promise 就是第一道防线。
它不是万能的——如果只是单次异步调用且后续无依赖,直接用 async/await 更自然;但理解 Promise 是用好 async/await 的前提,因为后者本质是 Promise 语法糖。
Promise 实例一创建就处于 pending 状态,之后只能变成 fulfilled(成功)或 rejected(失败),且不可逆。这个不可变性决定了你不能“重试”一个已 settle 的 Promise,必须新建。
new Promise((resolve, reject) => {...}) 构造函数里必须调用 resolve() 或 reject(),否则状态永远卡在 pending
.then(onFulfilled, onRejected) 中的 onRejected 不会捕获 onFulfilled 内抛出的错误,要靠链式调用后的下一个 .catch() 或第二个参数.catch() 等价于 .then(null, onRejected),但更常用,也更易读const p = new Promise((resolve, reject) => {
setTimeout(() => {
Math.random() > 0.5 ? resolve('done') : reject(new Error('fail'));
}, 100);
});
p.then(result => console.log(result))
.catch(err => console.error(err.message));
这是最容易出错的地方:每个 .then() 回调的返回值,会自动包装成新的 Promise,并决定下一级的状态。
.then() 的 onFulfilled 接收到该值Promise 实例 → 下一个 .then() 等待它 settle 后,接收其 resolve 的值Promise.reject(...) → 下一个 .then() 的 onRejected 被触发,或被后续 .catch() 捕获Promise.resolve(1) .then(x => x + 1) // 返回 2 → 下一级收到 2.then(x => Promise.resolve(x * 2)) // 返回 Promise(4) → 下一级收到 4 .then(x => { throw new Error('boom') }) .catch(err => console.log(err.message)); // 'boom'
Promise 链一旦断开(比如某个 .then() 里没 return),后续步骤就收不到值;而错误如果没有被任何 .catch() 捕获,会变成 unhandled rejection,现代浏览器或 Node.js 会直接报错退出进程。
async 函数里用 try/catch 捕获错误,比在 Promise 链末尾加 .catch() 更可靠Promise.all([p1, p2, p3]) 任意一个 reject 就整体失败;需要全部结果不管成败,改用 Promise.allSettled()
arr.map(x => fetch(x))),除非你明确要并发发起请求真正难的不是写对第一个 Promise,而是保证整条链的错误有出口、值能正确透传、并发控制不越界。这些细节在真实项目里比语法本身消耗更多调试时间。