1

I'm detecting if a value has been stored in localStorage (if localStorage exists), and if it's not in the database (or the user does not have a browser with localStorage) then I run an AJAX GET request.

if (Modernizr.localstorage) {
    // there is storage
    artist = localStorage.getItem('artist');
    if (!artist) {
        // but no cache
        artist = fetchArtist();
        localStorage.setItem('artist', artist)
    }
} else {
    // there's no storage
    artist = fetchArtist();
}
function fetchArtist() {
    var fetchedArtist;
    var recentTracks;
    $.get('script.php', [], function(data) {
        recentTracks = data.recenttracks;
        fetchedArtist = ((recentTracks !== undefined) ? recentTracks.track.artist['#text'] : 'Last.fm connection failed.');
    }, 'json');
    return fetchedArtist;
}

script.php just gets a JSON string, which jQuery converts in to the data object. I can see the problem: because $.get is async, the fetchedArtist variable is returned before the function can assign the value I'm after, but I can't think of a tidy way of doing this (global vars maybe, but I'd really rather not). I can console.log the fetchedArtist var inside $.get and the value I'm after, but the fetchArtist functions always returns undefined.

1 Answer 1

2

You have to asyncronize your workflow by removing the return statements from the fetchArtist() function because it cannot do what you need because of the async behaviour of the $.get request.

Try something like this:


if (Modernizr.localstorage) {
    // there is storage
    var artist = localStorage.getItem('artist');
    if (!artist) {
        // but no cache
        fetchArtist();
    } else {
        doWhatYouNeedWithArtist( artist );
    }
} else {
    // there's no storage
    fetchArtist();
}

function fetchArtist() {
    var fetchedArtist;
    var recentTracks;
    $.get('script.php', [], function(data) {
        recentTracks = data.recenttracks;
        fetchedArtist = ((recentTracks !== undefined) ? recentTracks.track.artist['#text'] : 'Last.fm connection failed.');
        if ( Modernizr.localstorage ) {
                Modernizr.localstorage.setItem('artist', fetchedArtist);
        }
        // then do your stuff
        doWhatYouNeedWithArtist( fetchedArtist );
    }, 'json');
}

function doWhatYouNeedWithArtist( artists ) {
    // do stuff
}

Hope this helps! Ciao.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.