In some specific scenarios (for example 即时搜索
, 表格分页
), Ajax requests are frequently initiated, and since Ajax is an asynchronous API, the returned timing is not guaranteed, and it is time to implement an AJAX queue that cancels processing the previous request when the same request is initiated.
When used jquery.ajax
, it is possible to interrupt processing of the Ajax return value in a more convenient abort
way, but because axios
it is dependent, it can promise
only be interrupted by the way it is converted Promsie.reject
. The specific code is as follows:
ImportAxios from ' Axios ';ImportQs from ' QS ';//error handling file defined in previous articleImportHttperrorhandler from './httperrorhandler ';ConstInstance= Axios.Create();//Request QueueConstQueue=[];//Axios built-in method for interrupting AjaxConstCanceltoken= Axios.Canceltoken;//stitching The requested URL and method, the same url+ method can be considered the same requestConstToken=(config)=>{ return `${Config.URL}_${Config.Method}`}//Interrupts duplicate requests and removes them from the queueConstRemovequeue=(config)= { for( LetI=0,Size= Queue.length;I<Size;I++){ ConstTask=Queue[i]; if(Task.token === token(config)){ Task.Cancel(); Queue.Splice(I, 1); } }}//Add request blockerinstance.Interceptors.Request. Use(config=>{ Removequeue(config); //Request for the same name before interruption //Add Canceltoken Config.Canceltoken = New Canceltoken((c)=>{ Queue.Push({ token: token(config), Cancel:C});}); returnConfig;},Error= { return Promise.Reject(Error);});//Add response blockerinstance.Interceptors.Response. Use(Response=>{ //After the request is complete, automatically move out of the queue Removequeue(Response.Config); return Response.Data},Httperrorhandler);/*** Post-Packaged Ajax post method * * @param {string}URL Request Path * @param {Object}Data Request Parameters * @param {Object}Config user custom settings * @returns */ function Post(URL,Data,Config= {})= { return instance.Post(URL,Data,Config}/*** Post-packaged Ajax get method * * @param {string}URL Request Path * @param {Object}Params Request Parameters * @param {Object}Config user custom settings * @returns */ function Post(URL,Params,Config= {})= { return instance.Get(URL, {Params},Config}Export default {Post,Get,}
Queue Application
Queues are typically combined with function stabilization to avoid errors in the order of return values in cases where the number of requests is minimized
$(input). on(' input ',Evt= { //In the user's continuous input process, when the pause input 100ms to launch Ajax, while initiating Ajax, interrupt the last query keyword Ajax debounce(()=>{ Get(' http://baidu.com ', {keyword: evt.Target.value})})})//Define an anti-shake functionfunction debounce*f,,Step= -){ LetTimeout= NULL; return function(){ cleartimeout(timeout);Timeout= SetTimeout(()= { fn.Apply( This,Arguments; },Step; };}
Axios Package (ii)-Queue management