javascript - Multiple ajax request in sequence using recursive function and execute callback function after all requests completed -
i have list of names separated comma. want want call server request names in sequence , store result inside array. tried , it's working when have number of names there in string.
see here - working when know number of names
now want want make code generic. if add 1 name in string, should handle automatically without adding code ajax request.
see here - i've tried. it's not working expected.
shoppinglist = shoppinglist.split(","); var result = []; function fetchdata(shoppingitem) { var s1 = $.ajax('/items/'+shoppingitem); s1.then(function(res) { result.push(new item(res.label,res.price)); console.log("works fine"); }); if(shoppinglist.length == 0) { completecallback(result); } else { fetchdata(shoppinglist.splice(0,1)[0]); } } fetchdata(shoppinglist.splice(0,1)[0]);
problem
i not getting how detect promise object have been resolved can call callback function.
to make ajax requests in sequence, have put recursive call in callback:
function fetchlist(shoppinglist, completecallback) { var result = []; function fetchdata() { if (shoppinglist.length == 0) { completecallback(result); } else { $.ajax('/items/'+shoppinglist.shift()).then(function(res) { result.push(new item(res.label,res.price)); console.log("works fine"); fetchdata(); // ^^^^^^^^^^^ }); } } fetchdata(); }
or use promises , do
function fetchlist(shoppinglist) { return shoppinglist.reduce(function(resultpromise, shoppingitem) { return resultpromise.then(function(result) { return $.ajax('/items/'+shoppingitem).then(function(res) { result.push(new item(res.label,res.price)); return result; }); }); }, $.when([])); }
notice there nothing in requirements of task ajax requests made sequentially. let them run in parallel , wait of them finish:
function fetchlist(shoppinglist) { $.when.apply($, shoppinglist.map(function(shoppingitem) { return $.ajax('/items/'+shoppingitem).then(function(res) { return new item(res.label,res.price); }); })).then(function() { return array.prototype.slice.call(arguments); }) }
Comments
Post a Comment