When several ajax calls are made

Below is a script that does not work in the order I want:

var masterData = {}; var tableNames = ['table1','table2','table3','table4','table5','table6']; var pullSqlData = function(){ tableNames.forEach(function(value) { if(storage.isEmpty(value)) { $.getJSON('http://domain.com?r=appsync/read&id='+value+ "&callback=", function(data){ masterData[value] = data; storage.set(value,data); }); } else { masterData[value] = storage.get(value); } }); }; $.when(pullSqlData()).done(function(){ console.log('all done'); }); 

After searching, I know that I can work higher if I manually do something like

 $.when( $.getJSON('http://domain.com?r=appsync/read&id=table1&callback=', function(data){ masterData[value] = data; storage.set(value,data); }), $.getJSON('http://domain.com?r=appsync/read&id=table2&callback=', function(data){ masterData[value] = data; storage.set(value,data); }), //more calls ).done(function(){ console.log('all done'); }); 

However, I was wondering if there is a way to make the right path higher.

* storage is an HTML5 localStorage jQuery plugin

+6
source share
3 answers

Since you are a dynamic number of queries, try

 var masterData = {}; var tableNames = ['table1', 'table2', 'table3', 'table4', 'table5', 'table6']; var pullSqlData = function () { var requests = []; tableNames.forEach(function (value) { if (storage.isEmpty(value)) { var xhr = $.getJSON('http://domain.com?r=appsync/read&id=' + value + "&callback=", function (data) { masterData[value] = data; storage.set(value, data); }); requests.push(xhr) } else { masterData[value] = storage.get(value); } }); return requests; }; $.when.apply($, pullSqlData()).done(function () { console.log('all done'); }); 

You need to pass all ajax requests to $.when() , so pullSqlData should return a list of the ajax requests it created. Also, $ .when () does not accept an array as arguments, so you need to use Function.apply () to pass a variable number of parameters to it

+5
source

Check every success

 var masterData = {}; var tableNames = ['table1', 'table2', 'table3', 'table4', 'table5', 'table6']; var pullSqlData = function () { var requests = []; tableNames.forEach(function (value) { if (storage.isEmpty(value)) { var xhr = $.getJSON('http://domain.com?r=appsync/read&id=' + value + "&callback=", function (data) { masterData[value] = data; storage.set(value, data); check_if_all_done(); }); requests.push(xhr) } else { masterData[value] = storage.get(value); } }); return requests; }; function check_if_all_done() { if(masterData.length == tableNames.length ) console.log('done'); } 
0
source

Something like this should work to streamline the requests:

 var requests = pullSqlData() //save in array of promises each request as @ArunPJhonny var first = requests.shift(); $.each(requests, function (n, p) { first.then(function () { return p; }); }); first.done(function () { //...done }); 
0
source

Source: https://habr.com/ru/post/959442/


All Articles