javascript - Executing ajax queries in a loop followed by a function that uses their combined output -
i have ajax query followed functions, , use .then() promise callback execute them in order:
var pictures = []; var venues = **an array of venues** $.get(url).then(functiona, functionfail).then(function b); but functiona, first success callback, includes loop fires off 'n' ajax requests:
for(var i=0; i<n; i++) { var venue = venues[i]; var new_url = **some_url** $.ajax({url: new_url, async: false}).done(function(data) { var pics = data.response.photos.items; pictures.push(pics[0]); pictures.push(pics[1]); }).fail(function() { console.log('failed!'); }); } these looped ajax requests fill global pictures array. pictures array used functionb, because of async nature, array doesn't filled , executes right away.
i tried make requests synchronous async: false it's not effective (it leaves out last request of loop).
how can make sure functionb executed after ajax requests have finished? don't want use timeouts if nothing else i'll fall on that.
you can use promise.all, code of function a:
var requests = [] for(var i=0; i<n; i++) { var venue = venues[i]; var new_url = **some_url** request.push(new promise((resolve, reject) => { $.ajax({url: new_url}).done(function(data) { var pics = data.response.photos.items; resolve(pics) }).fail(function(err) { reject(err) console.log('failed!'); }); })) } return promise.all(requests) when request run successful, whole return values of requests pushed array , passed function b.
Comments
Post a Comment