在 JavaScript 中,Promise
的多个 .then()
是链式调用的,值可以通过返回值的方式,在多个 .then()
之间传递。这是 Promise 链式调用的核心机制。
基本原理:每个 then
接收上一个 then
的返回值
new Promise((resolve, reject) => {
resolve(10); // 初始值
})
.then((value) => {
console.log("第一个 then 收到:", value); // 10
return value * 2;
})
.then((value) => {
console.log("第二个 then 收到:", value); // 20
return value + 5;
})
.then((value) => {
console.log("第三个 then 收到:", value); // 25
});
输出:
第一个 then 收到: 10
第二个 then 收到: 20
第三个 then 收到: 25
每个
.then()
的返回值会作为下一个.then()
的输入参数。
如果某个 then
返回的是 Promise?
如果某个 .then()
返回一个新的 Promise,那么下一个 .then()
会在该 Promise 成功解决(fulfilled) 后执行,并接收到它的 resolve
值。
new Promise((resolve) => resolve(10))
.then((value) => {
console.log("第一个 then:", value); // 10
return new Promise((resolve) => setTimeout(resolve, 1000, value * 2));
})
.then((value) => {
console.log("第二个 then(1秒后):", value); // 20
});
多个异步操作串行执行(链式传值)
你可以利用这种特性来串行处理多个异步任务:
function step1(value) {
return new Promise((resolve) => {
setTimeout(() => {
console.log("Step 1:", value);
resolve(value + 1);
}, 1000);
});
}
function step2(value) {
return new Promise((resolve) => {
setTimeout(() => {
console.log("Step 2:", value);
resolve(value * 2);
}, 1000);
});
}
function step3(value) {
return new Promise((resolve) => {
setTimeout(() => {
console.log("Step 3:", value);
resolve(value - 5);
}, 1000);
});
}
step1(5)
.then(step2)
.then(step3)
.then((finalResult) => {
console.log("最终结果:", finalResult); // (5+1)*2 -5 = 7
});
错误处理:catch 捕获链中任意错误
Promise.resolve(10)
.then((val) => {
console.log(val);
throw new Error("出错了!");
})
.then(() => {
console.log("不会执行");
})
.catch((err) => {
console.error("捕获错误:", err.message);
});
小结:如何传值?
场景 | 如何传值 |
---|---|
同步返回值 | 直接 return value |
异步返回值 | return new Promise(...) |
终止链或跳转 | 抛出异常 throw error 或返回 rejected Promise |
多个值传递? | 返回对象或数组,如 return { a, b } |
示例:带多个值传递的 Promise 链
Promise.resolve({ name: "Alice", age: 10 })
.then((person) => {
person.age += 1;
return person;
})
.then((person) => {
console.log(`${person.name} 现在 ${person.age} 岁了`);
});
如果你需要更复杂的流程控制,比如并行、条件分支等,也可以结合 Promise.all
、async/await
来实现。