链式调用
每次调用完返回this
javascript
const num = 10;
class Chain {
constructor(value) {
this.value = value;
}
addOne() {
this.value = this.value + 1;
return this;
}
addTwo() {
this.value = this.value + 2;
return this;
}
addThree() {
this.value = this.value + 3;
return this;
}
}
const chain = new Chain(num);
const result = chain.addOne().addTwo().value;
console.log(result); // 16
const num = 10;
class Chain {
constructor(value) {
this.value = value;
}
addOne() {
this.value = this.value + 1;
return this;
}
addTwo() {
this.value = this.value + 2;
return this;
}
addThree() {
this.value = this.value + 3;
return this;
}
}
const chain = new Chain(num);
const result = chain.addOne().addTwo().value;
console.log(result); // 16
Promise的链式调用
Promise 链式调用是指每个 then 方法返回的 Promise 实例都与前一个 Promise 实例关联,并且每个 then 方法注册的 onFulfilled 都返回了不同的结果。
实现 Promise 链式调用:
创建新的 Promise 实例
:在 then 方法中,我们需要创建一个新的 Promise 实例,并将其作为结果返回。下一个 then 方法就可以接收到这个新的 Promise 实例,并继续执行。状态传递
:当前 Promise 变为 fulfilled 或 rejected 状态时,将这个状态传递给下一个 Promise。下一个 then 方法就可以根据当前的状态来执行相应的逻辑。值传递
:除了状态传递外,我们还需要将当前 Promise 的值传递给下一个 Promise。下一个 then 方法就可以根据这个值来执行相应的操作。