jquery - How to store data inside a javascript foreach "loop" so that it can be accessed outside of the "loop" -
this question has answer here:
- how return response asynchronous call? 21 answers
i want store data properties inside "randomimages" object (this randomimages object used in function later) inside jquery foreach "loop". find data missing after loop finishes (inside ajax callback, data there). seems sort of scope or context issue don't know wrong. exact code using 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 lot of data here }); $('p').text(randomimages.tosource()); //why randomimages empty here?
the problem is: invoke function depends on async computation without wait it. moving computation inside callback should resolve, since data available @ 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 need use data n
functions recomend use promises, overwishe need move $.get callback. https://developer.mozilla.org/en-us/docs/web/javascript/reference/global_objects/promise
Comments
Post a Comment