Juicy
Juicy

Reputation: 12520

Deferred getJSON's return is undefined

It's the first time I attempt to do a deferred function and I'm clearly getting something wrong. I got a bit confused as there's apparently several ways of doing this but I tried working from the simplest I could find

Get_JSON( my_url ).done(function(data) {
    console.log( data['name'] );
});

function Get_JSON( url ) {
    var def = $.Deferred();
    $.getJSON(url).done(function(data){
        console.log( data['name'] );
        def.resolve({
            data:data
        });
    });
    return def;
}

My console output is:

John
undefined

(John being the expected name)

I suspect it's the def.resolve part that I'm getting wrong.

Upvotes: 1

Views: 216

Answers (2)

tcooc
tcooc

Reputation: 21219

Your main issue is that you're using the wrong key:

Do:

Get_JSON( my_url ).done(function(data) {
    console.log( data.data['name'] );
});

However, you can simplify your code to this:

Get_JSON( my_url ).done(function(data) {
    console.log( data['name'] );
});

function Get_JSON( url ) {
    return $.getJSON(url);
}

Or even to this:

$.getJSON(my_url).done(function(data) {
    console.log( data['name'] );
});

Basically, $.getJSON already returns a Deferred object, and your code is adding redundancy by proxying it.

Upvotes: 3

pomeh
pomeh

Reputation: 4912

This is the correct behavior. In your resolve call, you're passing an object {data: data} (let's called it object A), so it's an object which has a data key, and which value is the data object from the $.getJSON(url).done callback (let's call it object B). This last object has a name key, but the object you retrieve in your Get_JSON( my_url ).done callback is the object A (which has only a data key) and not the object B.

You should have write your code like this:

Get_JSON( my_url ).done(function(data) {
    console.log( data['name'] );
});

function Get_JSON( url ) {
    var def = $.Deferred();
    $.getJSON(url).done(function(data){
        console.log( data['name'] );
        def.resolve(data); // here is the only difference
    });
    return def;
}

Upvotes: 1

Related Questions