javascript - How to do sequential asynchronous ajax requests with given number of streams -
i need create sequential asynchronous ajax requests limited streams. of allowed occupy 1 stream on web server can 1 ajax request @ time.
i have next function helps me when allowed utilize 1 stream @ time.
function initiatechain() { var = 0; var tasks = arguments; var callback = function () { += 1; if (i != tasks.length) { tasks[i](callback); //block should phone call callback when done otherwise loop stops } } if (tasks.length != 0) { tasks[0](callback); //initiate first 1 } }
say if have 3 ajax helper functions
function getgadgets(callback) { //ajax phone call callback(); // phone call in finish callback of $.ajax } function getbooks(callback) { //ajax phone call callback(); // phone call in finish callback of $.ajax } function getdeals(callback) { //ajax phone call callback(); // phone call in finish callback of $.ajax }
following phone call ensures no more 1 ajax request made client
initiatechain(getgadgets, getbooks, getdeals);
now need enhance initiatechain back upwards arbitrary number of streams. allowed utilize 2 or n number of streams know ideas without changing ajax helper functions getgadgets, getdeals, getdeals.
in short, have set of functions, n, in case getgadgets, getdeals , getdeals(|n|=3) each need connection web server. currently, can execute 1 request @ time, initiatechain function calls 3 methods in sequence. if had access m connections, execute |n| functions in parallel (up maximum of m).
if you're using jquery can utilize .queue method queue ajax calls , execute them in sequence. run multiple sequences, can wrap initial dequeue in loop.
function add_api_call_to_queue(qname, api_url) { $(document).queue(qname, function() { $.ajax({ type : 'get', async : true, url : api_url, datatype : 'json', success : function(data, textstatus, jqxhr) { // activate next ajax phone call when 1 finishes $(document).dequeue(qname); } }); }); } $(document).ready(function() { var queue_name = 'a_queue'; var concurrent_calls = 2; // add together first ajax phone call queue add_api_call_to_queue(queue_name, '/example/api/books'); // add together sec ajax phone call queue add_api_call_to_queue(queue_name, '/example/api/dvds'); // add together 3rd ajax phone call queue add_api_call_to_queue(queue_name, '/example/api/shoes'); // start ajax queue (i=0;i<concurrent_calls;i++) { $(document).dequeue(queue_name); } })
javascript ajax
No comments:
Post a Comment