回调嵌套导致"回调地狱",代码难以阅读和维护。Promise 把异步操作包装成对象,支持链式调用。
pending:进行中fulfilled:已成功rejected:已失败状态一旦从 pending 改变,就不可逆。
const fetchData = (id) => new Promise((resolve, reject) => {
setTimeout(() => {
if (id > 0) resolve({ id, name: '张三' });
else reject(new Error('无效 id'));
}, 100);
});
fetchData(1)
.then(data => {
console.log(data);
return fetchData(2); // 返回新 Promise 继续链
})
.then(data2 => console.log(data2))
.catch(err => console.error(err))
.finally(() => console.log('结束'));
// 全部成功才继续
Promise.all([p1, p2, p3]).then(console.log);
// 谁先完成用谁
Promise.race([p1, p2]).then(console.log);
// 不中断地全部执行
Promise.allSettled([p1, p2]).then(results => {
results.forEach(r => console.log(r.status, r.value || r.reason));
});
async function getData() {
try {
const a = await fetchData(1);
const b = await fetchData(a.id);
return b;
} catch (err) {
console.error(err);
}
}
要点:async/await 让异步代码像同步一样可读,本质仍是 Promise。记得用 try/catch 捕获异常。