我试图使用AbortController():https://axios-http.com/docs/cancellation中止任何/所有以前的Axios请求
失败:在我的测试中,以前的查询不会被中止。
搜索体验仍然像预期的那样工作,但是当用户大量使用过滤器时,每个请求都会被完全消化。相反,我希望所有以前的请求都被中止。
我希望避免构建使用存储/跟踪请求、令牌和/或承诺的逻辑。我对这些东西很熟悉,我可以建造它,但我只想避免所有这些。
Axios的AbortController就是为此目的而设计的吗?
更新(工作): Thx到@Oluwafemi,我的设置正在工作。
有两件事必须改变:
附带注意:此外,这里没有包含一个关闭器,它封装了我的查询函数(在我的应用程序中),它与这个AbortController一起使用,为与API服务器的传出/传入通信进行了良好的多层管理。
(我编辑了一些与此无关的方法/行)
export default class MySearch {
constructor() {
// ONE-TIME SETUP
this.payload = null
this.active = {
q: "", // (Query) string e.g. "apples"
facets: {}, // Objects, each with array of options e.g. { 'size': [ '2 x 2 in', '3 x 3 in' ]}, { 'artists': [ 'mike', 'john', 'jane' ] }
page: null, // number e.g. 3
sortBy: null // string, one of: "default" | "newest" | "price_asc" | "price_desc"
}
// Declaring this here. Good/bad?
this.AxiosSearchController = new AbortController()
}
async query() {
return new Promise( async (resolve, reject) => {
// Abort any previous Axios request
this.AxiosSearchController.abort()
// Reinstantiate another instance of AbortController()
this.AxiosSearchController = new AbortController()
this.transformURL()
let requestParams = {
"page": this.active.page,
"sortBy": this.active.sortBy,
"filter": this.active.facets,
}
// Here we tell Axios to associate the request with the controller.
let AxiosSignal = {
signal: this.AxiosSearchController.signal
}
axios.post('/api/search/' + this.active.q, requestParams, AxiosSignal)
.then( response => {
this.payload = response.data
return resolve(response)
})
.catch( error => {
console.error(error)
return reject(error)
})
})
}
}发布于 2022-07-06 13:57:46
为AxiosSearchController初始化MySearch的位置取决于您是否希望MySearch的多个实例保持相同的搜索状态或维护自己的搜索状态。
在构造函数中初始化时,MySearch的每个实例都有自己的搜索状态,就像在代码段中一样。
1. Instance 1 initialized
2. Instance 2 initialized
3. Instance 3 initialized
4. Instance 1 performs request
5. Instance 2 performs request
6. Instance 3 performs request
7. Instance 1 aborts request
8. Instance 2 continues request till fulfillment
9. Instance 3 continues request till fulfillment在构造函数之外初始化时,MySearch的所有实例都保持相同的搜索状态。
1. Instance 1 initialized
2. Instance 2 initialized
3. Instance 3 initialized
4. Instance 1 performs request
5. Instance 2 performs request
6. Instance 1 has request aborted
7. Instance 3 performs request
8. Instance 2 has request aborted在params参数中提供signal属性是为axios库的请求设置信号的适当格式。
但是,当中止任何先前的请求时,AxiosSearchController.signal.aborted会被设置为true。
如果不重置中止控制器的此状态,您就不能在信号第一次中止后提出任何进一步的请求。
您需要在中止上一次搜索的请求后初始化AxiosSearchController。
this.AxiosSearchController.abort();
this.AxiosSearchController = new AbortController();https://stackoverflow.com/questions/72874576
复制相似问题