2

I want to store some data as properties inside the "randomImages" object (this randomImages object will be used in another function later) inside a jquery foreach "loop". But I find that the data is missing after the loop finishes (inside the ajax callback, the data is there). It seems like some sort of scope or context issue but I don't know what is wrong. The exact code I am using is below.

var randomImages = {};

$.get('http://pixabay.com/api/?username=bhinbox0&key=8792f764c13d09a7b7d2&q=yellow+flower&image_type=photo', function (data) {
    $.each(data.hits, function (index, entry) {
        randomImages[entry.webformatURL] = 'center';
    });
    //randomImages.toSource() shows a lot of data here
});

$('p').text(randomImages.toSource()); //why is randomImages empty here?
  • 4
    `$.get()` is asynchronous. Put the last statement inside the `$.get()` callback handler. – Ja͢ck Jun 15 '15 at 07:04
  • @Ja͢ck I need to use that data in another function further down, so I need to retain data in the variable randomImages. –  Jun 15 '15 at 07:06
  • put that another function as call back. – Shekhar Joshi Jun 15 '15 at 07:07
  • 1
    Then put whatever is "further down" inside the callback function as well. – Ja͢ck Jun 15 '15 at 07:07
  • @Ja͢ck the "further down" code is not under my control. basically, I have to provide a randomImages object in that particular format for use by other parts of the program. –  Jun 15 '15 at 07:10
  • 2
    [Highly recommended question](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call/14220323#14220323) to read before continuing. – Ja͢ck Jun 15 '15 at 07:10
  • @Ja͢ck Thanks for the help, that was my exact problem –  Jun 15 '15 at 07:12

1 Answers1

3

The problem is: you are invoke a function that depends on a async computation without wait for it. Moving this computation to inside get callback should resolve, since the data is available at callback execution.

var randomImages = {};
$.get('http://pixabay.com/api/?username=bhinbox0&key=8792f764c13d09a7b7d2&q=yellow+flower&image_type=photo', function (data) {
    $.each(data.hits, function (index, entry) {
        randomImages[entry.webformatURL] = 'center';
    });
    $('p').text(randomImages.toSource());

});

If you need use this data for N functions I recomend you to use Promises, overwishe you will need to move everything into $.get callback. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

Mateus Vahl
  • 979
  • 2
  • 12
  • 29