Question

Part of my application is rendered using data from a JSONP request. I would like to be able to cache the result of this request client-side using Sammy.Session.

However, I'm having some difficulty, since a JSONP request is synchronous. Here's my current, non-working code :

this.get('#/projects', function(context) {
    var categories = this.session('categories', function() {
        var data;
        $.getJSON('http://mysite.com/projects/categories/?jsoncallback=?', null,
            function(json) {
                data = json.categories;
            });
            return data;
         });
    });

    // categories is undefined at this point,
    // because the JSONP call may not have finished

    // code that renders the data

    this.session('categories', categories);
});

What I would like to not have to do is make the JSONP request if the categories are in session. Is there a way I can make the rest of the route's code wait until the JSONP request is finished?

Was it helpful?

Solution

The only way I could think of to solve this was to not try to leverage a callback if the session isn't found, and leverage a shared function callable from the result the JSON request or if the session is available. If someone knows a better way to accomplish this, I would love to see an example.

this.get('#/projects', function(context) {
    ...

    var categories = this.session('categories');

    if (categories == undefined) {
        this.load('http://mydomain.com/projects/categories/?jsoncallback=?',
            {dataType: 'json'})
            .then(function(json) {
                context.session('categories', json.categories);
                // call to shared function
            });
    }
    else {
        // call to shared function
    }
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top