推荐答案
// www.javascriptcn.com code example
const promise = new Promise((resolve, reject) => {
// 异步操作
setTimeout(() => {
const success = true;
if (success) {
resolve("操作成功");
} else {
reject("操作失败");
}
}, 1000);
});
promise
.then((result) => {
console.log(result); // 输出: 操作成功
})
.catch((error) => {
console.error(error); // 输出: 操作失败
})
.finally(() => {
console.log("操作完成"); // 无论成功或失败都会执行
});本题详细解读
then 方法
then 方法用于处理 Promise 成功时的回调。它接收两个参数:
- 第一个参数是
onFulfilled回调函数,当 Promise 状态变为fulfilled时调用。 - 第二个参数是
onRejected回调函数,当 Promise 状态变为rejected时调用(通常不推荐使用,而是使用catch方法)。
promise.then(
(result) => {
console.log(result); // 成功时执行
},
(error) => {
console.error(error); // 失败时执行
}
);catch 方法
catch 方法用于处理 Promise 失败时的回调。它相当于 then(null, onRejected) 的简写形式。
promise.catch((error) => {
console.error(error); // 失败时执行
});finally 方法
finally 方法用于在 Promise 无论成功还是失败后都会执行的回调。它不接收任何参数,通常用于清理操作。
promise.finally(() => {
console.log("操作完成"); // 无论成功或失败都会执行
});链式调用
then、catch 和 finally 方法可以链式调用,每个方法都会返回一个新的 Promise,允许你继续处理后续的操作。
// www.javascriptcn.com code example
promise
.then((result) => {
console.log(result); // 成功时执行
return "新的数据";
})
.then((newResult) => {
console.log(newResult); // 输出: 新的数据
})
.catch((error) => {
console.error(error); // 失败时执行
})
.finally(() => {
console.log("操作完成"); // 无论成功或失败都会执行
});