promise值穿透
在JavaScript中,Promise的“值穿透”(Value Chaining)是指在Promise链中,通过.then()方法返回的值可以被链中的下一个.then()函数接收的特性。这意味着你可以在Promise链中传递值,并且每个.then()函数都能访问到前一个.then()函数返回的值。
const promise1 = Promise.resolve(1);
promise1
.then(result => {
console.log(result); // 输出: 1
return result + 1;
})
.then(result => {
console.log(result); // 输出: 2
return result + 1;
})
.then(result => {
console.log(result); // 输出: 3
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
在这个例子中,每个.then()函数返回一个新的值,并且这个值被传递给链中的下一个.then()函数。
# 值穿透的规则
返回值:每个
.then()函数的返回值会成为下一个.then()函数的参数。隐式解析:如果
.then()函数返回一个值,那么这个值会被自动包装在一个新的Promise对象中,并且这个Promise对象会被解析为这个返回值。返回Promise:如果
.then()函数返回一个Promise对象,那么链中的下一个.then()函数将等待这个Promise对象解析或拒绝后再执行。非值返回:如果
.then()函数没有返回值(或者返回undefined),那么下一个.then()函数的参数将是undefined。错误传递:如果
.then()函数中抛出错误,那么链中的下一个.then()函数将不会执行,而是跳转到链中的.catch()方法(如果有的话)来处理错误。
# 使用async/await的值穿透
在async/await语法中,值穿透的行为与.then()类似,但是更加简洁和直观。
async function example() {
const result1 = await promise1; // result1为1
const result2 = await result1 + 1; // result2为2
const result3 = await result2 + 1; // result3为3
console.log(result3); // 输出: 3
}
example();
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
在这段代码中,await关键字用于等待Promise解析,并且解析后的值可以被直接使用。
# 总结
值穿透是Promise链式调用的一个关键特性,它允许你在Promise链中传递值,并且使得异步操作的流程控制更加灵活和方便。无论是使用.then()方法链,还是使用async/await语法,都可以通过值穿透来实现复杂的异步流程。
上次更新: 2025/09/05, 8:09:00