Axios promise在我尝试使其可取消时返回错误

bfrts1fy  于 2023-11-18  发布在  iOS
关注(0)|答案(1)|浏览(134)

我遇到了一个问题,一个特定的请求可能需要太长的时间才能返回数据,所以我一直在考虑让promise“cancellable”,以便在我更改请求的过滤器后忽略它。我意识到Axios中现在有取消请求的功能,但我正在做的项目有一个非常过时的版本,没有这个功能。不久前,我找到了this并将其“Typescript-ified”为这个;

export function makeCancellable<T, F>(fn: (param: T, options?: any) => AxiosPromise<F>) {
    let reject_: (reason?: any) => void; // cache for the latest `reject` executable
    return function(param: T, options?: any) {
        if(reject_) reject_(new Error('_cancelled_')); // If previous reject_ exists, cancel it.
                                                       // Note, this has an effect only if the previous race is still pending.
        let canceller = new Promise<AxiosResponse<F>>((_, reject) => { // create canceller promise
            reject_ = reject; // cache the canceller's `reject` executable
        });
        return Promise.race([canceller, fn(param, options)]); // now race the promise of interest against the canceller
    }
}

字符串
现在,当我尝试使promise可取消时,它返回TypeError: Cannot read properties of undefined (reading 'configuration')。OpenAPI用于生成这些请求,我按如下方式发出请求:

cancellableRequest = makeCancellable(this.api.request);


这是在一个服务类中,并在构造函数中示例化(因此没有constvar等)。然后当我调用该函数来启动promise时,它会返回该错误。

d5vmydt9

d5vmydt91#

我认为这是因为我不再从它来自的上下文调用函数,所以解决方案只是在它来自的API类的上下文中传递。
因此,我不得不使用fn.apply(api, [param, options])而不是fn(param, options)。所要做的就是将API上下文作为any传递给makeCancellable函数。我不是100%确定它是如何工作的,所以这是我目前给予的最好解释。

相关问题