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...

5
  • 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. Commented Jan 23, 2012 at 17:12
  • data is a Document object though right? I thought I could pass that into $() in order to query it? Commented Jan 23, 2012 at 17:19
  • Oh, sorry, confused the console.log output. Commented Jan 23, 2012 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 in the question itself, both so the question is self-contained and in case the linked page goes down, goes away or gets edited. Commented Jan 24, 2012 at 4:08
  • possible duplicate of Return value from function with an Ajax call, Return value from ajax call?, How can I return a variable from a $.getJSON function. Commented Jan 24, 2012 at 4:11

1 Answer 1

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);

});
Sign up to request clarification or add additional context in comments.

1 Comment

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!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.