Two questions:
1. There are three Ajax requests, how to get these three Ajax requests serial execution, that is, after the first execution completes the other.
2. How to get them to execute in parallel, and then perform an operation after three requests have been completed.
Serial execution is divided into two types.
One is to use synchronous mode Async:false, three Ajax requests to write on it.
$.ajax ({URL: "Ajax request 1", Async:false, Success:function (data) {Console.log ("Ajax request 1 complete");
}
});
$.ajax ({URL: "Ajax request 2", Async:false, Success:function (data) {Console.log ("Ajax request 2 Complete");
}
});
$.ajax ({URL: "Ajax request 3", Async:false, Success:function (data) {Console.log ("Ajax request 2 Complete");
}
});
The second is to use asynchronous mode Async:true, three AJAX requests nested write.
$.ajax ({URL: "Ajax request 1", Async:true, Success:function (data) {Console.log ("Ajax request 1 complete");
$.ajax ({URL: "Ajax request 2", Async:true, Success:function (data) {
Console.log ("Ajax request 2 Complete"); $.ajax ({URL: "Ajax request 3", Async:true, Success:function (data)
{Console.log ("Ajax request 3 complete"); }
});
}
});
}
}); Parallel execution can only be done in asynchronous mode.
and set the variable to count var num = 0;
function isallsuccess () {num++;
if (num>=3) Console.log ("All three Ajax requests complete"); } $.ajax ({URL: Ajax request 1, Async:true, success:function (data) {Console.log ("Ajax request 1 Complete")
;
Isallsuccess ();
}
});
$.ajax ({URL: "Ajax request 2", Async:true, Success:function (data) {Console.log ("Ajax request 3 complete");
Isallsuccess ();
}
});
$.ajax ({URL: "Ajax request 3", Async:true, Success:function (data) {Console.log ("Ajax request 3 complete");
Isallsuccess (); }
});
At present, promise can be used in ES6. Then chain can also implement multilayer asynchronous callback problem, ES7 async and await are solved. The complex writing of the then chain. Await is the value of waiting for a promise object or an expression; if await waits for a promise object, it blocks the following code to wait for the Promise object resolve, and so on resolve completes returning the resolve result to the implementation callback In this way, with a aync and multiple await can easily complete multi-layer nested asynchronous callback, and elegant, simple code.
My GitHub has the case source code: HTTPS://GITHUB.COM/SPICYBOILEDFISH/JAVASCRIPT-TESTJS/BLOB/MASTER/53. A comprehensive understanding of the promise.html in ES6
For detailed details, please see the following two blog posts:
The promise:http://www.cnblogs.com/lvdabao/p/es6-promise-1.html in the ES6
Async and await:http://blog.csdn.net/hj7jay/article/details/61191416 in the ES7