我已经研究了一段时间,我觉得解决方案必须非常明显,但我想不出来。
我有一个函数 (getImage),在该函数内部我有一个 getJSON 函数。我对 API 调用返回的数据做了一些处理,然后返回它,所以我返回的值是我想要的实际数据,但是我如何让父函数 (getImage) 也返回该值?
var getImage = function(urlforAPI) {
$.getJSON(urlforAPI, function(imageData) {
console.log(imageData);
for (x in imageData.query.pages) {
if (imageData.query.pages[x].hasOwnProperty("thumbnail")) {
var storyImage = "<img src=" + imageData.query.pages[x].thumbnail.source + ">";
} else {
var storyImage = "No image.";
}
}// End FOR loop
console.log(storyImage); //This is logging the data I need
return storyImage;
})//End of getJSON
//What do I return here to get the same value that the child function returned?
}// End getImage
如果重要的话,我将在另一个函数中调用这个函数并将其存储为 var tempImage = getImage(theURL)
。我传递给它的参数是在我调用它的函数内部生成的。我将使用 tempImage
将 getImage
的值输出到 DOM。
如何获取从 getJSON 子函数返回的值以在调用时从 getImage
返回?
我读了这个javascript child function pass the return to the parent function return但我不完全明白 callback(true)
/callback(false)
位在做什么。
最佳答案
在第一个函数中初始化变量,在嵌套函数中设置它,然后返回它。
var storyImage = "";
$.getJSON(urlforAPI, function(imageData) {
console.log(imageData);
for (x in imageData.query.pages) {
if (imageData.query.pages[x].hasOwnProperty("thumbnail")) {
storyImage = "<img src=" + imageData.query.pages[x].thumbnail.source + ">";
} else {
storyImage = "No image.";
}
}// End FOR loop
console.log(storyImage); //This is logging the data I need
})//End of getJSON
关于javascript - 从父函数返回什么以获取从子函数/嵌套函数返回的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34277218/