const myPromise = new Promise((resolve, reject) => {
// 模拟一个异步任务(比如一个API请求)
setTimeout(() => {
const success = true;
if (success) {
resolve("任务成功完成!"); // 操作成功,调用 resolve
} else {
reject("任务失败。"); // 操作失败,调用 reject
}
}, 1000);
});
function good(result) {
console.log("成功的结果是:", result);
}
function bad(error) {
console.error("出现错误:", error);
}
const onFinally = () =>
console.log("Promise 执行结束。不论成功还是失败都会执行这段。");
// 使用 .then() 和 .catch() 处理结果
myPromise
.then(good)
.catch(bad)
.finally(onFinally);
展开/折叠结果
成功的结果是: 任务成功完成!
执行结束。不论成功还是失败都会执行这段。
// 定义函数
function firstThen(result) {
console.log("第一次 then:", result);
return result * 2; // 返回值会传递到下一步
}
function secondThen(result) {
console.log("第二次 then:", result);
return result * 3; // 返回值会传递到下一步
}
function thirdThen(result) {
console.log("第三次 then:", result);
// 这里是最后一步,你可以不返回值
}
// 主逻辑:调用 Promise 并使用函数
new Promise((resolve) => {
resolve(1); // 初始化 Promise,传递值 1
})
.then(firstThen) // 调用第一个函数
.then(secondThen) // 调用第二个函数
.then(thirdThen); // 调用第三个函数
展开/折叠结果
第一次 then: 1
第二次 then: 2
第三次 then: 6
发表评论