Previously encountered a business needs, the need to rely on the order to perform an unlimited number of ajax request to the server.
We know that in general JS asynchronous callback ajax function execution order cannot be guaranteed.
I used the queues and recursive methods based on jQuery to initially implement callback functions that sequentially execute asynchronous ajax requests.
If wrong, please criticize and correct :)
<script type="text/javascript">
$(document).ready(function() {
// Executes multipleajax commands in order, using a recursion because of the indefinite number
function send (action, arg2) {
// Encapsulate multiplecommands into array objects in sequence and execute them recursively
// Use the deferredobject to control the callback function
$ .when (send_action (action [0],arg2))
.done ( function () {
//Before ajax callback function to determine the length of the queue
if (action.length> 1) {
//queue length greater than 1, the first pop-up, continue to recursively executethe queue
action.shift ();
send (action,arg2);
}
}). fail ( function () {
//Queue elements in the request after the failure of the logic
//
//retry sending
//send (action, arg2);
//
//Ignore the error before proceeding
// if(action.length> 1) {
//queue length greater than 1, the first pop-up, continue to recursively executethe queue
//action.shift ();
//send (action, arg2);
//}
});
}
// handle each command'sajax request and callback function
function send_action (command, arg2) {
var dtd = $ .Deferred ();
$ .post (
"url",
{
command: command,
arg2: arg2
}
) .done ( function (json) {
json = $ .parseJSON(json);
// Processinglogic for each callback function
//
//
//
// Logicalend
dtd.resolve ();
}). fail ( function () {
// ajax The logicof the request failed
dtd.reject ();
});
return dtd.promise (); //Returns the promise of a Deferred object, preventing external modification ofthe state
}
});
</script>
Post your comments / questions
Recent Article
- Your system's memory configuration has changed since it entered hibernation.
- Save image to client browser using jQuery?
- Get filename of image jQuery?
- How to get the image src using JavaScript?
- System.Net.Http.Formatting, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' which has a higher version than referenced assembly 'System.Net.Http.Formatting' with identity 'System.Net.Http.Formatting, Version=4.0.0.0
- Cordova Android build error "Cannot read property 'length' of undefined". An error occurred while running subprocess cordova.
- ERROR in The Angular Compiler requires TypeScript >=3.9.2 and <4.0.0 but 3.8.3 was found instead
- Code ENOLOCAL Could not install from "android" as it does not contain a package.json file.
Related Article