1
我一直在完成FreeCodeCamp並給自己提供了從維基百科API獲取圖像的任務。我很親密,但我只是遇到了這個遞歸函數的麻煩。如何在函數遞歸時返回父函數Javascript
我在使用ajax請求時遇到了一些麻煩。我希望整個成功函數在obj ===標籤時返回。但是,它只返回findObjByLabel()的一個實例。
一旦找到標籤,我能做些什麼來使成功函數完全返回?
var wikiUrl = "https://en.wikipedia.org/w/api.php?action=query&format=json&titles=India&prop=pageimages&pithumbsize=300&callback=?";
// this retrieves info about the wikiUrlImg
$.ajax({
url: wikiUrl,
data: {
format: 'json'
},
dataType: 'json',
type: 'GET',
headers: { 'Api-User-Agent': 'Example/1.0' },
success: function(data) {
console.log("wiki api success");
var findLabel = findObjByLabel(data,"India",1);
function findObjByLabel(obj, label, iterrations){
var itterationLimit = "9";
if (iterrations < itterationLimit){
for(var i in obj){
if(obj === label){
console.log(">>>>>>>>>>>>>>>>>>>>>>> !!!its the label!!! <<<<<<<<<<<<<<<<<<<<<<<<");
// ****************I want the success function to return here! ****************
return "something";
}else{
console.log(">>>>>>>>>>>>>>>>>>>>>>>its not the label<<<<<<<<<<<<<<<<<<<<<<<<");
console.log("i= " + i);
if(obj.hasOwnProperty(i)){
iterrations+=1;
console.log("obj[i] : " + obj[i]);
var foundLabel = findObjByLabel(obj[i], label, iterrations);
}
}
}
}
}//end of findObjByLabel function
}, //end of success
error: function(){
console.log("failure of getWiki api");
}
});
你爲什麼不只是檢查返回值在'findObjByLabel'外面並返回? – Chintan
你不能在異步函數中返回。 – BenG
_「我能做些什麼來使成功函數完全返回,一旦標籤被找到?」_你是什麼意思「成功函數完全返回」是$ .ajax()'調用鏈接到'.done ()'或'.then()'? – guest271314