0

Possible Duplicate:
Return value from ajax call?
JavaScript asynchronous return value / assignment with jQuery

I have a problem whereby I am trying to iterate over an array in JavaScript, but for some reason it is failing to do so. I am building the array in a $.get() callback from last.fm's API and creating an array of objects. When I then try to iterate over the array afterwards, it doesn't work and the length is zero.

I've posted a JSFiddle here:

http://jsfiddle.net/MMps2/2/

Any thoughts? I'm going a bit mad here!

Note: Pop up your JS console - I'm logging stuff to it...

Community
  • 1
  • 1
  • 1
    You can't expect an asynchronous setup to work like that. The "results" object won't be built until that API call is completed. The code around the `$.get()` however will not wait for that to happen. – Pointy Jan 23 '12 at 17:12
  • data is a Document object though right? I thought I could pass that into $() in order to query it? – Andy Mantell Jan 23 '12 at 17:19
  • Oh, sorry, confused the `console.log` output. – Felix Kling Jan 23 '12 at 17:20
  • While it's very helpful to link to an external page with code so people can play with it, that shouldn't take the place of having [minimal sample code](http://sscce.org/) in the question itself, both so the question is self-contained and in case the linked page goes down, goes away or gets edited. – outis Jan 24 '12 at 04:08
  • possible duplicate of [Return value from function with an Ajax call](http://stackoverflow.com/questions/562412/), [Return value from ajax call?](http://stackoverflow.com/a/1632088/90527), [How can I return a variable from a $.getJSON function](http://stackoverflow.com/questions/31129/). – outis Jan 24 '12 at 04:11

1 Answers1

3

Your $.get request runs asynchronously. You're trying to return the value of results before it even gets a chance to execute. Instead, use a callback pattern to call another function when the get request is done.

EDIT: Example:

// Fetch top artists for the passed in username
$.get('http://ws.audioscrobbler.com/2.0/', {method: 'user.getTopArtists', user: user, api_key: 'c2c920e0749f24f2661d54614335748d'}, function(data) {

    // No need to use your higher scope results variable anymore
    var results = [];

    $('artist', data).each(function(index, artist) {

        // For each artist in the result, build an object containing the artists name and MusicBrainz ID
            results.push({
                'name': $('name', artist).text(),
                'mbid': $('mbid', artist).text()
        });

    });

    // Here's where such a call would go
    sendResultsToWhateverObjectNeedsThem(results);

});
Jimmy Theis
  • 448
  • 3
  • 8
  • Ah yes, that makes sense. I knew $.get was asynchronous but I've been staring at it for hours and couldn't see it! I wanted it to be a nice generic function, hence my wanting to "return" the results. I've changed it now so that the original function takes an extra argument where you can specify your callback. Thanks for the help! – Andy Mantell Jan 23 '12 at 17:31