Node.js Promise
Promise 是处理异步操作的对象,代表一个未来完成或失败的操作结果。
创建 Promise
JavaScript
// 基本创建
const promise = new Promise((resolve, reject) => {
// 异步操作
setTimeout(() => {
const success = true;
if (success) {
resolve('操作成功');
} else {
reject(new Error('操作失败'));
}
}, 1000);
});
// 快捷创建
const resolved = Promise.resolve('成功');
const rejected = Promise.reject(new Error('失败'));
Promise 状态
| 状态 | 说明 | 特点 |
|---|---|---|
| pending | 进行中 | 初始状态 |
| fulfilled | 已完成 | 不可变,有结果值 |
| rejected | 已拒绝 | 不可变,有错误原因 |
JavaScript
const p = new Promise((resolve) => {
resolve('完成');
resolve('再次完成'); // 无效,状态已确定
});
then 和 catch
JavaScript
promise
.then((result) => {
console.log('成功:', result);
return result.toUpperCase();
})
.then((upper) => {
console.log('转换:', upper);
})
.catch((err) => {
console.error('错误:', err.message);
});
// then 接收成功结果,catch 捕获错误
链式调用
JavaScript
// 每个 then 返回新 Promise
fetchData()
.then(processData)
.then(saveData)
.then(showResult)
.catch(handleError);
// 返回值会传递给下一个 then
Promise.resolve(1)
.then(n => n + 1) // 2
.then(n => n * 2) // 4
.then(console.log); // 4
Promise.all
JavaScript
// 并行执行,全部成功才返回
const promises = [
fetch('/api/users'),
fetch('/api/posts'),
fetch('/api/comments')
];
Promise.all(promises)
.then(results => {
const [users, posts, comments] = results;
console.log(users, posts, comments);
})
.catch(err => {
console.error('任意一个失败:', err);
});
Promise.race
JavaScript
// 返回最先完成的结果(成功或失败)
Promise.race([
fetch('/api/fast'),
new Promise((_, reject) =>
setTimeout(() => reject(new Error('超时')), 5000)
)
])
.then(result => console.log('成功:', result))
.catch(err => console.error('失败或超时:', err));
Promise.allSettled
JavaScript
// 等待所有 Promise 完成,返回每个结果
Promise.allSettled([
Promise.resolve('成功1'),
Promise.reject('失败1'),
Promise.resolve('成功2')
])
.then(results => {
results.forEach(r => {
console.log(r.status, r.value || r.reason);
});
// fulfilled 成功1
// rejected 失败1
// fulfilled 成功2
});
错误处理
JavaScript
// catch 捕获链中任意错误
Promise.resolve()
.then(() => {
throw new Error('抛出错误');
})
.then(() => {
console.log('不会执行');
})
.catch(err => {
console.log('捕获:', err.message);
return '恢复';
})
.then(result => {
console.log('继续:', result); // '恢复'
});
始终在 Promise 链末尾添加 catch,避免未处理的拒绝。
要点总结
- Promise 有三种状态:pending、fulfilled、rejected
- then 处理成功,catch 处理失败
- Promise.all 并行等待全部完成
- Promise.race 返回最先完成的结果
- 链式调用中 catch 可恢复后续执行
📝 发现内容有误?点击此处直接编辑