2015-12-14 90 views
2

我一直在這一點工作,我覺得解決方案必須非常明顯,但我不明白出。什麼從父函數返回從子函數返回的值/嵌套的函數

我有一個函數(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)位正在做什麼。

回答

1

初始化第一個函數中的變量,將其設置在嵌套函數中,然後返回它。

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 
+0

好吧,我只是試過這個。當我在父函數中返回''myResult''',然後調用父函數時,它將返回一個對象而不是子函數返回的字符串。當我在返回語句之前記錄myResult時,它返回'''Object:{readyState:1}'''。 – Chirpizard

+0

啊,這就是AJAX readyState ...我已經更新了我的答案:) – Rhono

+0

好的,我試過了新的解決方案。當我從父函數返回時,我只是得到空字符串。如果我從孩子返回,我會得到所需的值(從API調用返回的URL,或者else語句的「無圖像」)。 – Chirpizard