You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Axios中CancelToken.js重写promise.then的代码作用是什么?

解答Axios CancelToken中重写Promise.then的逻辑及你的Demo问题

你的Demo未触发预期输出的原因

你的Demo存在顺序错误:你先调用了原生的p.then(),之后才重写p.then方法。因此当你执行resolve(1)时,触发的是之前注册的原生then回调,重写后的then方法从未被调用,自然不会打印‘I am here’。

修正后的Demo需要先重写then,再调用它:

let resolve
let p = new Promise((res, rej) => resolve = res)
// 先重写then方法
p.then = onFulfill => {
  console.log('I am here')
  const promise = new Promise(resolve => {
    resolve(2)
  }).then(onFulfill)
  return promise
}
// 再调用重写后的then
p.then(val => {
  console.log('In p.then ', val)
})
console.log(p.then)
resolve(1)

运行这段代码就会打印‘I am here’和‘In p.then 2’,符合你的预期。

Axios CancelToken中那段代码的作用

这段代码的核心是给每个通过then注册的回调绑定独立的取消能力:

  1. 重写this.promise的then方法后,每次调用cancelToken.promise.then(onFulfilled)时,都会创建一个新的内部Promise。
  2. 内部Promise会先订阅CancelToken的回调(token.subscribe(resolve)),当CancelToken触发取消操作时,会调用这个resolve,进而执行后续的onFulfilled。
  3. 同时给返回的新Promise添加cancel方法,调用该方法会取消订阅对应的resolve回调(token.unsubscribe(_resolve)),这样即使CancelToken后续触发取消,这个回调也不会再执行。

简单来说,这段代码实现了精细的回调取消控制:每个基于CancelToken promise的then链式调用,都能独立取消自己的回调,避免一次取消操作影响所有注册的回调。

内容的提问来源于stack exchange,提问作者Jiangqi Zhu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 09:40:25