[英]Ajax API call inside a while loop inside a for loop?
因此,我正在為一個類進行API混搭。 現在,我從Google Maps API收到json響應。 我通過使用for循環從響應中獲得5個航點。 我要解決的問題是某些坐標在死角中並且沒有與它們關聯的圖片。 我想在4個迭代中的每個迭代上進行ajax調用,但是如果一個沒有圖片,它將迭代直到找到一個圖片,然后返回到上次中斷的地方。 我嘗試使用while循環,以便進行調用,並在成功協調時將while循環變量設置為true,然后它將脫離while循環,然后返回for循環進行迭代到下一個“路標”。 截至目前,我還沒有收到錯誤消息,該網站正在超時,也許有太多呼叫? 也許我正在遞歸地做某事?
// so this for loop divides the hundreds of steps by 1/4 of the total length.
for (i=0; i<polyPoints.length; i+=quarters) {
// gets the coords for the current iteration.
var lat = polyPoints[i][0];
var lng = polyPoints[i][1];
var hasPic = false;
var origI = i;
//while loop runs through and checks to see if the coordinate has pictures at it.
while (hasPic == false){
$.ajax({
type : "GET",
dataType : "jsonp",
ajaxI: i,
url: 'https://api.instagram.com/v1/media/search?lat='+lat+'&lng='+lng+'&distance=5000&access_token='+token,
success: function(data){
i = this.ajaxI;
//if null,increases the iteration by one, and then runs through the loop again, checking the next coordinate? I hope.
if(typeof data.data[0] === "undefined" || data.meta.code == 400){
i++;
console.log("i increased to "+i);
}else{
//if the pic is there then it assigns a random picture from the result to the images array.
images.push(data.data[Math.floor(Math.random() * data.data.length)].images.low_resolution.url);
//sets while loop to stop
hasPic = true;
//loads the current iterations coordinates for the later for loop to create markers.
waypoints.push([lat,lng]);
}
}, //data.data[0].images.low_resolution.url
error: function(data){
i = this.ajaxI;
i++;
//images.push(img/test.jpg");
}
}).responseText;
}//waypoints.push([lat,lng]);
//resets the i back to the original iteration before it got increased
i = origI;
}
這是我使用$.Deferred
嘗試:
function tryGetImage(firstI, maxI) {
var dfr = $.Deferred();
var inner = function(i) {
if(i >= maxI) dfr.reject();
var lat = polyPoints[i][0];
var lng = polyPoints[i][1];
$.ajax({
type : "GET",
dataType : "jsonp",
url: 'https://api.instagram.com/v1/media/search?lat='+lat+'&lng='+lng+'&distance=5000&access_token='+token,
}).done(function(data){
//if null,increases the iteration by one, and then runs through the loop again, checking the next coordinate? I hope.
if(typeof data.data[0] === "undefined" || data.meta.code == 400){
inner(i + 1);
}else{
var img = data.data[Math.floor(Math.random() * data.data.length)].images.low_resolution.url);
dfr.resolve(img, [lat, lng]);
}
).fail(function(data){
inner(i + 1);
});
};
inner(firstI);
return dfr.promise();
}
var dfrs = [];
for (i=0; i<polyPoints.length; i+=quarters) {
var dfr = tryGetImages(i, i + quarters)
dfr.done(function(img, coords) {
images.push(img);
waypoints.push(coords);
})
dfrs.push(dfr);
}
$.when.apply($, dfrs).always(function() {
console.log("All requests complete");
});
第14行的三等號(===)? 我想你的意思是==?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.